LocalDateTimeUtil.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #!/usr/bin/python3.6
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Copyright (C) 2022 #
  5. # @Time : 2022/3/26 16:20
  6. # @Author : ming
  7. # @Email : zhangdongming@asj6.wecom.work
  8. # @File : LocalDateTimeUtil.py
  9. # @Software: PyCharm
  10. import datetime
  11. import time
  12. import pendulum
  13. from datetime import datetime as dt2
  14. def get_last_first_date_and_last_date(n):
  15. """
  16. 获取前n周开始时间和结束时间,参数n:代表前n周
  17. """
  18. now = datetime.datetime.now()
  19. # 上周第一天和最后一天
  20. before_n_week_start = now - datetime.timedelta(days=now.weekday() + 7 * n, hours=now.hour, minutes=now.minute,
  21. seconds=now.second, microseconds=now.microsecond)
  22. # last_week_end = now - timedelta(days=now.weekday() + 1)
  23. before_n_week_end = before_n_week_start + datetime.timedelta(days=6, hours=23, minutes=59, seconds=59)
  24. return before_n_week_start, before_n_week_end
  25. def get_today_date(timestamp=False):
  26. """
  27. 返回当天开始时间和结束时间
  28. Args:
  29. timestamp 是否返回时间戳
  30. returns:
  31. zero_today ,last_today
  32. """
  33. now = datetime.datetime.now()
  34. zero_today = now - datetime.timedelta(hours=now.hour, minutes=now.minute, seconds=now.second,
  35. microseconds=now.microsecond)
  36. last_today = zero_today + datetime.timedelta(hours=23, minutes=59, seconds=59)
  37. if timestamp:
  38. zero_today = int(time.mktime(zero_today.timetuple()))
  39. last_today = int(time.mktime(last_today.timetuple()))
  40. return zero_today, last_today
  41. return zero_today, last_today
  42. def get_last_month():
  43. """
  44. 获取前一个月时间
  45. returns:
  46. last_month_date
  47. """
  48. today = datetime.date.today() # 1. 获取「今天」
  49. last_month = today.replace(month=today.month - 1) # 2.获取前一个月
  50. last_month_date = last_month.strftime("%Y-%m-%d %H:%M:%S")
  51. return last_month_date
  52. def date_to_week(str_date):
  53. """
  54. 日期获取星期几
  55. @param str_date 日期 例:2022-03-03
  56. @return: int 1-7
  57. """
  58. if str_date:
  59. dt = pendulum.parse(str_date).day_of_week
  60. dt = 7 if dt == 0 else dt
  61. return dt
  62. return datetime.datetime.now().weekday() + 1
  63. def convert_time_to_seconds(date_time):
  64. # 将时间字符串转换为datetime对象
  65. dt_obj = dt2.strptime(date_time, '%Y-%m-%d %H:%M:%S')
  66. # 提取小时、分钟和秒数
  67. hours = dt_obj.hour
  68. minutes = dt_obj.minute
  69. seconds = dt_obj.second
  70. # 计算总秒数
  71. total_seconds = hours * 3600 + minutes * 60 + seconds
  72. return total_seconds