[Python] 纯文本查看 复制代码 import datetime
def days_of_month(year, month):
if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
return 31
elif month == 4 or month == 6 or month == 9 or month == 11:
return 30
elif month == 2 and ((year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)):
return 29
else:
return 28
start_time = datetime.datetime(2004, 2, 20, 15, 15, 00)
print('开始时间:', start_time)
end_time = datetime.datetime.now()
print('结束时间:', end_time)
if end_time < start_time:
end_time, start_time = start_time, end_time
delta = end_time - start_time
y = end_time.year - start_time.year
m = end_time.month - start_time.month
d = end_time.day - start_time.day
h = end_time.hour - start_time.hour
mi = end_time.minute - start_time.minute
sec = end_time.second - start_time.second
if sec < 0:
mi -= 1
sec += 60
if mi < 0:
h -= 1
mi += 60
if h < 0:
d -= 1
h += 24
if d < 0:
m -= 1
d += min(days_of_month(end_time.year, end_time.month), days_of_month(start_time.year, start_time.month))
if m < 0:
y -= 1
m += 12
print(f'相差:{y}年 {m}月 {d}天 {h}时 {mi}分 {sec}秒')
|