python之如何计算两个日期相差天数days

电玩女神 2021-09-30 00:04 1067阅读 0赞

参考:https://jingyan.baidu.com/article/3f16e003211db12591c103a6.html

自己封装的一个方法【计算两个日期的差值】

  1. @classmethod
  2. # 把一个字符串格式的日期【2019-7-18】或【2019.7.18】转换成(2019,7,8)数字元组
  3. def date_str_to_number_tuple(cls, date_str):
  4. if "-" in date_str:
  5. [year, month, day] = date_str.split("-")
  6. elif "." in date_str:
  7. [year, month, day] = date_str.split(".")
  8. else:
  9. raise Fail(f"date_str日期字符串格式必须为[年-月-日]或[年.月.日]")
  10. return [int(year), int(month), int(day)]
  11. @classmethod
  12. # 计算两个日期相差多少天days
  13. def compute_two_date_offset_days(cls, start_date_str, end_date_str):
  14. start_year_month_day = cls.date_str_to_number_tuple(start_date_str)
  15. end_year_month_day = cls.date_str_to_number_tuple(end_date_str)
  16. return (datetime.date(*end_year_month_day) - datetime.date(*start_year_month_day)).days

参考资料:官方的date源代码兼容增删改查运算【内部实现了这些特殊方法】

  1. class date:
  2. min: ClassVar[date]
  3. max: ClassVar[date]
  4. resolution: ClassVar[timedelta]
  5. def __init__(self, year: int, month: int, day: int) -> None: ...
  6. @classmethod
  7. def fromtimestamp(cls, t: float) -> date: ...
  8. @classmethod
  9. def today(cls) -> date: ...
  10. @classmethod
  11. def fromordinal(cls, n: int) -> date: ...
  12. if sys.version_info >= (3, 7):
  13. @classmethod
  14. def fromisoformat(cls, date_string: str) -> date: ...
  15. @property
  16. def year(self) -> int: ...
  17. @property
  18. def month(self) -> int: ...
  19. @property
  20. def day(self) -> int: ...
  21. def ctime(self) -> str: ...
  22. def strftime(self, fmt: _Text) -> str: ...
  23. if sys.version_info >= (3,):
  24. def __format__(self, fmt: str) -> str: ...
  25. else:
  26. def __format__(self, fmt: AnyStr) -> AnyStr: ...
  27. def isoformat(self) -> str: ...
  28. def timetuple(self) -> struct_time: ...
  29. def toordinal(self) -> int: ...
  30. def replace(self, year: int = ..., month: int = ..., day: int = ...) -> date: ...
  31. def __le__(self, other: date) -> bool: ...
  32. def __lt__(self, other: date) -> bool: ...
  33. def __ge__(self, other: date) -> bool: ...
  34. def __gt__(self, other: date) -> bool: ...
  35. def __add__(self, other: timedelta) -> date: ...
  36. @overload
  37. def __sub__(self, other: timedelta) -> date: ...
  38. @overload
  39. def __sub__(self, other: date) -> timedelta: ...
  40. def __hash__(self) -> int: ...
  41. def weekday(self) -> int: ...
  42. def isoweekday(self) -> int: ...
  43. def isocalendar(self) -> Tuple[int, int, int]: ...

发表评论

表情:
评论列表 (有 0 条评论,1067人围观)

还没有评论,来说两句吧...

相关阅读