import datetime
# from datetime import date
# 1. 获取当前时间 2024-06-06 17:30:20.733408
print(datetime.datetime.now())
# 2. 获取当前日期 2024-06-06
today = datetime.date.today()
# 获取年月日
print(today.year)
print(today.month)
print(today.day)
# 3. 实例化日期 2000-01-01
print(datetime.date(2000, 1, 1))
# 4. 日期的比较
time1 = datetime.date(2000, 1, 1)
time2 = datetime.date(2000, 10, 1)
print("**************")
# 将字符串转为datetime类型
str_time = "2000-01-01"
fmt = "%Y-%m-%d"
datetime_time = datetime.datetime.strptime(str_time,fmt)
print(datetime_time, type(datetime_time))
print("==============")
# 将datetime类型转为字符串格式
time_datetime = datetime.datetime.now()
fmt = "%Y-%m-%d %H:%M:%S"
time_str = time_datetime.strftime(fmt)
print(time_str,type(time_str))
print("**************")
# 两个时间是否相等 False
print(time1.__eq__(time2))
# 第一个日期是否大于等于第二个 False
print(time1.__ge__(time2))
# 第一个日期是否大于第二个 False
print(time1.__gt__(time2))
# 第一个日期是否小于等于第二个 True
print(time1.__le__(time2))
# 第一个日期是否小于第二个 True
print(time1.__lt__(time2))
# 第一个日期不等于第二个 True
print(time1.__ne__(time2))
# 5. 两个日期的差值
print(time1.__sub__(time2).days) # -274
print(time1.__rsub__(time2).days) # 274
标签:__,python,time1,time2,datetime,模块,time,print
From: https://www.cnblogs.com/Leybxin-AXB/p/18316848