跳转到内容
新建笔记

times

time 是 Python 标准库模块;旧标题中的 times 不是这里要导入的名字。日历时间、当地时间和经过时长是不同问题,先选对时钟,再做格式转换。

入口输入与结果使用边界
time.time()返回自 epoch 起的秒数适合时间戳;系统校时可能使它跳变,不用它保证耗时单调
time.ctime(seconds)时间戳转当地时间字符串省略参数时用当前时间;不是 UTC 格式
time.localtime(seconds)时间戳转当地 struct_time使用进程所在环境的时区规则
time.gmtime(seconds)时间戳转 UTC struct_timeUTC 反向转换用 calendar.timegm
time.sleep(seconds)暂停当前线程可能晚于请求时间恢复,不是精确调度保证
time.strftime(format, tuple)时间元组转字符串第二参数不是裸时间戳,先用 localtime 或 gmtime 转换
time.strptime(text, format)字符串转 struct_time无时区的文本本身没有指定唯一时间戳;不匹配会报 ValueError
time.mktime(tuple)当地时间元组转时间戳不是 gmtime 的 UTC 逆函数;夏令时折返时可能有歧义
time.perf_counter()高分辨率经过时间计数只比较两次读数之差,包括 sleep;不是日历时间戳

原表把 strftime 描述成可直接接收时间戳,并把 perf_counter 的后续语句写在 # 注释之后;下面用完整程序分开检查。

import calendar
import time
stamp = 1717156800 # 2024-05-31 12:00:00 UTC
utc = time.gmtime(stamp)
assert time.strftime("%Y-%m-%d %H:%M:%S", utc) == "2024-05-31 12:00:00"
assert calendar.timegm(utc) == stamp
local = time.localtime(stamp)
assert time.mktime(local) == stamp
assert time.ctime(stamp) == time.asctime(local)
parsed = time.strptime("2024-05-31 12:00:00", "%Y-%m-%d %H:%M:%S")
assert parsed[:6] == (2024, 5, 31, 12, 0, 0)
assert isinstance(time.time(), float)
try:
time.strftime("%Y", stamp)
except TypeError:
pass
else:
raise AssertionError("strftime unexpectedly accepted a timestamp")
try:
time.strptime("not a date", "%Y-%m-%d")
except ValueError:
pass
else:
raise AssertionError("invalid date unexpectedly parsed")
print("UTC:", time.strftime("%Y-%m-%d %H:%M:%S", utc))
print("local:", time.ctime(stamp))
start = time.perf_counter()
time.sleep(0.01)
elapsed = time.perf_counter() - start
assert elapsed >= 0 # 不要求调度器恰好在10毫秒恢复,也不据此测CPU耗时。
print("elapsed seconds:", elapsed)

这里固定时刻的当地时间回环不是所有夏令时边界的证明。若业务需要命名时区、重复小时或带时区的日期计算,使用 datetime 和 zoneinfo 并明确歧义处理。平台支持的日期范围和格式指令也可能不同。本次在 Linux Python 3.12 执行示例,未改系统时钟或系统时区。

依据:Python time。