HowardZhangdqs's picture
懒得写commit了
ccb6afe
from datetime import date as dt_date, timedelta
class Date:
def __init__(self, *args):
if len(args) == 0:
self._date = dt_date.today()
elif len(args) == 1:
s = args[0]
if isinstance(s, str):
if 'T' in s:
date_part = s.split('T')[0]
else:
date_part = s
self._date = dt_date.fromisoformat(date_part)
else:
raise TypeError("Invalid argument type. Expected string.")
elif len(args) == 3:
year, month, day = args
self._date = dt_date(year, month, day)
else:
raise TypeError("Date() requires 0, 1, or 3 arguments")
def __eq__(self, other):
if isinstance(other, Date):
return self._date == other._date
return False
def __add__(self, days):
if isinstance(days, int):
new_date = self._date + timedelta(days=days)
return Date(new_date.year, new_date.month, new_date.day)
else:
return NotImplemented
__radd__ = __add__
def __repr__(self):
return f"Date({self._date.year}, {self._date.month}, {self._date.day})"
def __str__(self):
return f"{self._date.year:04}-{self._date.month:02}-{self._date.day:02}"
# 小于
def __lt__(self, other):
if isinstance(other, Date):
return self._date < other._date
return False
# 小于等于
def __le__(self, other):
if isinstance(other, Date):
return self._date <= other._date
return False
# 大于
def __gt__(self, other):
if isinstance(other, Date):
return self._date > other._date
return False
# 大于等于
def __ge__(self, other):
if isinstance(other, Date):
return self._date >= other._date
return False
if __name__ == "__main__":
date1 = Date() # 返回今天日期
date2 = Date("2025-01-28")
date3 = Date(2025, 1, 28)
date4 = Date("2025-01-31T13:33:38.548Z") # 删除所有时间信息,仅保留日期
print(date2 == date3) # True
date4 = Date("2025-01-29")
print(date2 + 1 == date4)
print(date1, date2, date3, date4)
print(date1 < date2) # False