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

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

 

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

 @classmethod
    # 把一个字符串格式的日期【2019-7-18】或【2019.7.18】转换成(2019,7,8)数字元组
    def date_str_to_number_tuple(cls, date_str):
        if "-" in date_str:
            [year, month, day] = date_str.split("-")
        elif "." in date_str:
            [year, month, day] = date_str.split(".")
        else:
            raise Fail(f"date_str日期字符串格式必须为[年-月-日]或[年.月.日]")
        return [int(year), int(month), int(day)]

    @classmethod
    # 计算两个日期相差多少天days
    def compute_two_date_offset_days(cls, start_date_str, end_date_str):
        start_year_month_day = cls.date_str_to_number_tuple(start_date_str)
        end_year_month_day = cls.date_str_to_number_tuple(end_date_str)
        return (datetime.date(*end_year_month_day) - datetime.date(*start_year_month_day)).days

 

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

class date:
    min: ClassVar[date]
    max: ClassVar[date]
    resolution: ClassVar[timedelta]

    def __init__(self, year: int, month: int, day: int) -> None: ...

    @classmethod
    def fromtimestamp(cls, t: float) -> date: ...
    @classmethod
    def today(cls) -> date: ...
    @classmethod
    def fromordinal(cls, n: int) -> date: ...
    if sys.version_info >= (3, 7):
        @classmethod
        def fromisoformat(cls, date_string: str) -> date: ...

    @property
    def year(self) -> int: ...
    @property
    def month(self) -> int: ...
    @property
    def day(self) -> int: ...

    def ctime(self) -> str: ...
    def strftime(self, fmt: _Text) -> str: ...
    if sys.version_info >= (3,):
        def __format__(self, fmt: str) -> str: ...
    else:
        def __format__(self, fmt: AnyStr) -> AnyStr: ...
    def isoformat(self) -> str: ...
    def timetuple(self) -> struct_time: ...
    def toordinal(self) -> int: ...
    def replace(self, year: int = ..., month: int = ..., day: int = ...) -> date: ...
    def __le__(self, other: date) -> bool: ...
    def __lt__(self, other: date) -> bool: ...
    def __ge__(self, other: date) -> bool: ...
    def __gt__(self, other: date) -> bool: ...
    def __add__(self, other: timedelta) -> date: ...
    @overload
    def __sub__(self, other: timedelta) -> date: ...
    @overload
    def __sub__(self, other: date) -> timedelta: ...
    def __hash__(self) -> int: ...
    def weekday(self) -> int: ...
    def isoweekday(self) -> int: ...
    def isocalendar(self) -> Tuple[int, int, int]: ...

 

 

你可能感兴趣的:(Python)