时间计算

2022-12-21

datatime 时间计算

通过 timedelta 计算 datatime 时间,支持单位:

  • hours: 小时
  • seconds: 秒
1
from datetime import datetime, timedelta
2
3
local_time = datetime.now()
4
# 返回 datetime.datetime(2022, 1, 19, 0, 47, 51, 466384)
5
6
hours_ago = local_time - timedelta(hours=8)
7
# 返回 datetime.datetime (2022, 1, 18, 16, 43, 25, 870600

字符串时间计算

计算时间相差多少秒

1
def time_difference(update_time: str) -> float:
2
update_time = datetime.fromisoformat(update_time)
3
current_time = datetime.now()
4
5
diff_time = abs(current_time - update_time)
6
7
return diff_time.total_seconds()

常用功能模块

计算执行时间

方法一:使用 time

1
import time
2
3
start_time = time.time()
4
# Some code
5
end_time = time.time()
6
7
print(end_time - start_time)
8
# 返回:1.1920928955078125e-06

方法二:使用 datetime

1
import datetime
2
3
start_time = datetime.datetime.now()
4
# Some code
5
end_time = datetime.datetime.now()
6
7
print(end_time - start_time)
8
# 返回:0:00:00.000014