datatime 时间计算
通过 timedelta 计算 datatime 时间,支持单位:
- hours: 小时
- seconds: 秒
from datetime import datetime, timedelta
local_time = datetime.now()
# 返回 datetime.datetime(2022, 1, 19, 0, 47, 51, 466384)
hours_ago = local_time - timedelta(hours=8)
# 返回 datetime.datetime (2022, 1, 18, 16, 43, 25, 870600
字符串时间计算
计算时间相差多少秒
def time_difference(update_time: str) -> float:
update_time = datetime.fromisoformat(update_time)
current_time = datetime.now()
diff_time = abs(current_time - update_time)
return diff_time.total_seconds()
常用功能模块
计算执行时间
方法一:使用 time
import time
start_time = time.time()
# Some code
end_time = time.time()
print(end_time - start_time)
# 返回:1.1920928955078125e-06
方法二:使用 datetime
import datetime
start_time = datetime.datetime.now()
# Some code
end_time = datetime.datetime.now()
print(end_time - start_time)
# 返回:0:00:00.000014