123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- #!/usr/bin/python3.6
- # -*- coding: utf-8 -*-
- #
- # Copyright (C) 2022 #
- # @Time : 2022/3/26 16:20
- # @Author : ming
- # @Email : zhangdongming@asj6.wecom.work
- # @File : LocalDateTimeUtil.py
- # @Software: PyCharm
- import datetime
- import time
- import pendulum
- from datetime import datetime as dt2
- def get_last_first_date_and_last_date(n):
- """
- 获取前n周开始时间和结束时间,参数n:代表前n周
- """
- now = datetime.datetime.now()
- # 上周第一天和最后一天
- before_n_week_start = now - datetime.timedelta(days=now.weekday() + 7 * n, hours=now.hour, minutes=now.minute,
- seconds=now.second, microseconds=now.microsecond)
- # last_week_end = now - timedelta(days=now.weekday() + 1)
- before_n_week_end = before_n_week_start + datetime.timedelta(days=6, hours=23, minutes=59, seconds=59)
- return before_n_week_start, before_n_week_end
- def get_today_date(timestamp=False):
- """
- 返回当天开始时间和结束时间
- Args:
- timestamp 是否返回时间戳
- returns:
- zero_today ,last_today
- """
- now = datetime.datetime.now()
- zero_today = now - datetime.timedelta(hours=now.hour, minutes=now.minute, seconds=now.second,
- microseconds=now.microsecond)
- last_today = zero_today + datetime.timedelta(hours=23, minutes=59, seconds=59)
- if timestamp:
- zero_today = int(time.mktime(zero_today.timetuple()))
- last_today = int(time.mktime(last_today.timetuple()))
- return zero_today, last_today
- return zero_today, last_today
- def get_last_month():
- """
- 获取前一个月时间
- returns:
- last_month_date
- """
- today = datetime.date.today() # 1. 获取「今天」
- last_month = today.replace(month=today.month - 1) # 2.获取前一个月
- last_month_date = last_month.strftime("%Y-%m-%d %H:%M:%S")
- return last_month_date
- def date_to_week(str_date):
- """
- 日期获取星期几
- @param str_date 日期 例:2022-03-03
- @return: int 1-7
- """
- if str_date:
- dt = pendulum.parse(str_date).day_of_week
- dt = 7 if dt == 0 else dt
- return dt
- return datetime.datetime.now().weekday() + 1
- def convert_time_to_seconds(date_time):
- # 将时间字符串转换为datetime对象
- dt_obj = dt2.strptime(date_time, '%Y-%m-%d %H:%M:%S')
- # 提取小时、分钟和秒数
- hours = dt_obj.hour
- minutes = dt_obj.minute
- seconds = dt_obj.second
- # 计算总秒数
- total_seconds = hours * 3600 + minutes * 60 + seconds
- return total_seconds
|