Python 日期与时间:时间戳、格式化和日历
从同一秒数得到 UTC 和本地时间,再比较耗时计数器、日期格式符和月历网格。
学完这一章,你能够
- 从同一秒数得到 UTC 和本地时间,再比较耗时计数器、日期格式符和月历网格。
区分瞬间、民用日期和耗时
time.time() 返回 Unix 时间戳,单位为秒,可以带小数。纪元是 1970 年 1 月 1 日 00:00:00 UTC。这个时钟可能被系统调校。要测一个操作经过多久,用 perf_counter 的两次读数相减。要测当前进程耗费的 CPU 时间,使用 process_time 的差值。
时间戳可以为负。能否转换负值或 2038 年以后,取决于调用的函数和平台 C 库。本站 Windows 实验的 gmtime(-1) 能得到 1969 年最后一秒,localtime(-1) 则可能报 OSError。2038 年边界常见于使用 32 位有符号 time_t 的环境。需要做公历运算时也可用带 UTC 时区的 datetime 加 timedelta,避免依赖这些 C 库转换。
gmtime(ts) 将时间戳拆成 UTC 字段,localtime(ts) 使用系统本地时区。反向转换分别用 calendar.timegm 和 time.mktime。mktime 将输入解释为本地民用时间。夏令时切换时可能有重复或不存在的钟面时刻。交换数据时应保留显式时区偏移,或使用带时区的 datetime。
所需环境:本地 Python 3.12 与系统时区
当前源码 SHA256:58c399850debadab14cd775cbb975f24d2b9dcecf81c65866ebda2c2be2df949
所需环境:本地 Python 3.12 与系统时区
当前源码 SHA256:4b803aca5654715f4eabe59fc1b3ada5a00337edbe21e80d5009c5195b2c8b4a
读取九个字段并转换为文本
struct_time 可以按位置读九个整数,也可访问 tm_year、tm_mon 等命名字段。它使用周一为 0 的星期编号,年内日序从 1 开始。tm_isdst 为 1、0 或 -1 时,分别表示使用夏令时、未使用和未知。tm_zone 和 tm_gmtoff 是额外属性,不在这九个位置中。
asctime 接受时间元组,将日期和钟面时间按固定样式排成一行。ctime(ts) 等价于对 localtime(ts) 调用 asctime。两者都没有附带可靠的时区偏移。需要控制表示时,用 strftime 指定格式。strptime 按指定格式把文本还原成时间元组,字段缺省时从 1900-01-01 00:00:00 取值。解析后再调用 mktime,得到的时间戳仍按本地时区解释。
本站例子把固定的闰日转成数值格式和英文星期格式,再解析回字段。英文名称和 %c、%x、%X 受区域设置影响,实验临时选择 C locale 并还原。%U 以周日为起点,%W 以周一为起点,首个完整周之前记作第 00 周。%w 以周日为 0,和 tm_wday 的编号不同。%Z 只表示名称,不能可靠地还原偏移。
选择计时器和进度显示
旧程序的 time.clock() 在 Unix 上通常报告进程 CPU 时间,在 Windows 上是高精度经过时间。它在 Python 3.3 弃用,3.8 移除。按用途改成 process_time 或 perf_counter。perf_counter 的基准点未定义,差值包含 sleep。process_time 汇总本进程的用户态和系统态 CPU 时间,不把睡眠时间计作 CPU 时间。
下载实验文件和核对模块到同一目录,运行 python python3-date-time.py。加 --progress 会显示一个短进度条。每次刷新记录从同一 perf_counter 起点经过的秒数,并写入回车将光标移回行首,最后再写换行。支持回车重绘的终端会更新同一行,重定向文件则会保留回车字符。sleep 只暂停调用线程,调度可能让实际等待更长。
time.timezone 和 time.altzone 按 UTC 以西的秒数记录标准和夏令时偏移,符号与通常的 UTC+偏移写法相反。time.tzname 的第 0 项为标准时间名称,第 1 项为夏令时名称。需要某一时刻实际采用的名称和偏移时,读该时刻 localtime 的 tm_zone 和 tm_gmtoff。Unix 的 tzset 可重新读取 TZ,Windows 的标准库没有该接口。
生成文本日历和日期网格
calendar 按延伸公历生成月历和年历,默认周一开头。month 返回文本,monthcalendar 返回逐周的整数列表,月外空格对应 0。monthrange 返回该月第一天的星期和该月天数,weekday 查询任意指定日期的星期。公历整百年只有能被 400 整除时才是闰年。leapdays 的终点年份不计入。
改全局周起点会影响后续月历输出。库代码可创建 Calendar 或 TextCalendar 实例来单独指定周起点。prcal 和 prmonth 直接向标准输出写文字。w 控制日期列宽,l 控制每周占行,c 是年历中相邻月份的间隔,m 是每行月份个数。通过这些参数控制布局,避免把某一份输出的行宽当成固定公式。
时间元组索引和字段
| 索引 | 属性 | 含义 |
|---|---|---|
| 0 | tm_year | 公历年份,以完整年份表示。 |
| 1 | tm_mon | 月,1 到 12。 |
| 2 | tm_mday | 月内日,1 到该月最后一天。 |
| 3 | tm_hour | 24 小时制小时,0 到 23。 |
| 4 | tm_min | 分钟,0 到 59。 |
| 5 | tm_sec | 通常为 0 到 59。time 的历史接口还保留 60 与 61 的取值范围,61 仅为历史兼容。 |
| 6 | tm_wday | 周内日,0 为周一,6 为周日。 |
| 7 | tm_yday | 公历年内日序,1 到 365 或 366。 |
| 8 | tm_isdst | 1 表示夏令时,0 表示标准时间,-1 表示未知。 |
日期时间格式符
| 格式 | 含义 |
|---|---|
| %y | 两位年份。解析时 69 到 99 映射到 1969–1999,00 到 68 映射到 2000–2068。 |
| %Y | 完整年份。解析小于 1000 的年份时要补齐四位。 |
| %m | 月份,01 到 12。 |
| %d | 月内日,01 到 31,具体受年月约束。 |
| %H | 24 小时制,00 到 23。 |
| %I | 12 小时制,01 到 12,解析时配合 %p。 |
| %M | 分钟,00 到 59。 |
| %S | 通常为 00 到 59,time 接口还保留历史秒值范围。 |
| %a | 本地星期缩写。 |
| %A | 本地星期全名。 |
| %b | 本地月份缩写。 |
| %B | 本地月份全名。 |
| %c | 本地区域设置下的日期与时间。 |
| %j | 年内第几日,001 到 366。 |
| %p | 本地上午或下午标记,解析时和 %I 一起用。 |
| %U | 以周日开始计周,年初首个周日之前是第 00 周。 |
| %w | 周内日,0 表示周日,6 表示周六。 |
| %W | 以周一开始计周,年初首个周一之前是第 00 周。 |
| %x | 本地区域设置下的日期。 |
| %X | 本地区域设置下的时间。 |
| %Z | 本地时区名称,可为空。名称的解析能力因平台而异。 |
| %% | 字面百分号。 |
time 读数、转换与历史接口
| 接口 | 用法与返回值 |
|---|---|
| time.altzone | 整数属性,夏令时偏移的 UTC 以西秒数。有夏令时规则时才用它。 |
| time.asctime([t]) | 将九字段时间转成固定可读字符串。省略 t 时采用当前本地时间。 |
| time.clock() | 历史接口,依平台计 CPU 时间或经过时间。已移除,按用途改用下述计数器。 |
| time.ctime([secs]) | 返回本地可读时间字符串。省略 secs 时用当前时间。 |
| time.gmtime([secs]) | 将秒数转成 UTC 的 struct_time,tm_isdst 为 0。 |
| time.localtime([secs]) | 将秒数转成当地 struct_time,应用系统时区及规则。 |
| time.mktime(t) | 把本地时间九字段转成浮点时间戳。超出平台范围可能报错。 |
| time.sleep(secs) | 暂停调用线程,允许小数秒,返回 None。 |
| time.strftime(format[, t]) | 按格式输出时间文本。省略 t 时使用当前本地时间。 |
| time.strptime(text[, format]) | 按格式解析文本,返回 struct_time,无法匹配时报 ValueError。 |
| time.time() | 当前 Unix 时间戳,单位为秒,返回 float。 |
| time.tzset() | Unix 上重新读取 TZ 并更新进程的时间相关设置。 |
| time.perf_counter() | 经过时间计数器,读数相减得到秒数,包含休眠。 |
| time.process_time() | 当前进程 CPU 时间计数器,读数相减得到秒数,不含休眠。 |
time 时区属性
| 属性 | 含义 |
|---|---|
| time.timezone | 非夏令时时相对 UTC 以西的整数秒数。 |
| time.tzname | 二元字符串元组,依次为标准时间名称和夏令时名称。 |
calendar 年历与月历接口
| 接口 | 用法与返回值 |
|---|---|
| calendar.calendar(year, w=2, l=1, c=6, m=3) | 返回文本年历。w 控制日期列宽,l 控制每周占行,c 控制月间距,m 控制每行月份数。 |
| calendar.firstweekday() | 返回周起点,首次载入时为 0。 |
| calendar.isleap(year) | 按公历规则判断是否为闰年,返回布尔值。 |
| calendar.leapdays(y1, y2) | 统计从 y1 到 y2 前一年的闰年数量。 |
| calendar.month(year, month, w=0, l=0) | 返回文本月历。指定日期列宽与每周行数,实际排版有最小宽度和行数。 |
| calendar.monthcalendar(year, month) | 返回逐周的日期整数网格,月份外的位置为 0。 |
| calendar.monthrange(year, month) | 返回月初星期编号和月内天数。 |
| calendar.prcal(year, w=0, l=0, c=6, m=3) | 把年历文字写到标准输出。 |
| calendar.prmonth(year, month, w=0, l=0) | 把月历文字写到标准输出。 |
| calendar.setfirstweekday(weekday) | 设定模块函数的周起点,合法整数范围 0 到 6。 |
| calendar.timegm(t) | 按 UTC 解释时间元组并返回整数时间戳。 |
| calendar.weekday(year, month, day) | 返回给定公历日期的星期编号,周一为 0。 |
本章自编源码与运行范围
"""蓝色天空网 mbsky.com · 日期、时间戳、计时和日历实验。"""
import calendar
from contextlib import redirect_stdout
from datetime import datetime, timedelta, timezone
from io import StringIO
import locale
import os
from pathlib import Path
import platform
import sys
import time
sys.path.insert(0, str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks
def progress(stream, steps=4, delay=0.01):
start = time.perf_counter()
elapsed = []
for done in range(steps + 1):
filled = "#" * done
empty = "." * (steps - done)
seconds = time.perf_counter() - start
elapsed.append(seconds)
print(f"\r{100 * done // steps:3d}% [{filled}{empty}] {seconds:.3f}s",
end="", file=stream, flush=True)
if done < steps:
time.sleep(delay)
print(file=stream)
return elapsed
def inspect_clock(check, sample):
current = time.time()
check.eq("wall clock seconds are a float", type(current).__name__, "float")
check.eq("epoch in UTC", tuple(time.gmtime(0)), (1970, 1, 1, 0, 0, 0, 3, 1, 0))
check.eq("UTC represents negative epoch seconds", tuple(time.gmtime(-1))[:6],
(1969, 12, 31, 23, 59, 59))
check.eq("UTC crosses the signed 32 bit boundary", tuple(time.gmtime(2**31))[:6],
(2038, 1, 19, 3, 14, 8))
check.eq("UTC datetime arithmetic before epoch",
(datetime(1970, 1, 1, tzinfo=timezone.utc) - timedelta(seconds=1)).isoformat(),
"1969-12-31T23:59:59+00:00")
try:
before_epoch = tuple(time.localtime(-1))
except (OSError, OverflowError, ValueError) as exc:
before_epoch = type(exc).__name__
utc_fields = time.gmtime(sample)
check.eq("all nine UTC struct_time positions", tuple(utc_fields),
(2024, 2, 29, 15, 4, 5, 3, 60, 0))
check.eq("struct_time attribute names match indices",
tuple(getattr(utc_fields, "tm_" + name) for name in
("year", "mon", "mday", "hour", "min", "sec", "wday", "yday", "isdst")),
tuple(utc_fields))
check.eq("UTC timegm round trip", calendar.timegm(utc_fields), sample)
local_fields = time.localtime(sample)
check.eq("current time converts to struct_time", type(time.localtime(current)).__name__, "struct_time")
check.eq("local mktime round trip", time.mktime(local_fields), float(sample))
check.eq("offset reconstructs local civil time", calendar.timegm(local_fields) - sample,
local_fields.tm_gmtoff)
check.eq("asctime fixed space padding", time.asctime(time.gmtime(sample + 5 * 86400)),
"Tue Mar 5 15:04:05 2024")
check.eq("ctime uses local time", time.ctime(sample), time.asctime(local_fields))
check.eq("timezone and altzone are integer attributes",
(type(time.timezone).__name__, type(time.altzone).__name__), ("int", "int"))
check.eq("tzname has two string slots", tuple(type(x).__name__ for x in time.tzname), ("str", "str"))
if time.daylight == 0:
check.eq("standard time offset reverses timezone sign", local_fields.tm_gmtoff, -time.timezone)
check.eq("standard time name is tzname slot zero", local_fields.tm_zone, time.tzname[0])
if hasattr(time, "tzset"):
old = os.environ.get("TZ")
try:
os.environ["TZ"] = "UTC0"
time.tzset()
check.eq("tzset changes process local offset", time.localtime(sample).tm_gmtoff, 0)
finally:
if old is None:
os.environ.pop("TZ", None)
else:
os.environ["TZ"] = old
time.tzset()
else:
check.eq("Windows has no tzset", os.name, "nt")
return before_epoch
def inspect_formats(check, sample):
original = locale.setlocale(locale.LC_TIME)
try:
locale.setlocale(locale.LC_TIME, "C")
fields = time.gmtime(sample)
codes = ("%y", "%Y", "%m", "%d", "%H", "%I", "%M", "%S", "%a", "%A", "%b",
"%B", "%c", "%j", "%p", "%U", "%w", "%W", "%x", "%X", "%Z", "%%")
expected = ("24", "2024", "02", "29", "15", "03", "04", "05", "Thu", "Thursday",
"Feb", "February", None, "060", "PM", "08", "4", "09", None, None, None, "%")
formatted = {}
for code, target in zip(codes, expected, strict=True):
actual = time.strftime(code, fields)
formatted[code] = actual
if target is not None:
check.eq("format " + code, actual, target)
check.eq("format %c", tuple(time.strptime(formatted["%c"], "%c"))[:6], tuple(fields)[:6])
check.eq("format %x", tuple(time.strptime(formatted["%x"], "%x"))[:3], tuple(fields)[:3])
check.eq("format %X", tuple(time.strptime(formatted["%X"], "%X"))[3:6], tuple(fields)[3:6])
local_zone = time.localtime(sample)
check.eq("format %Z", time.strftime("%Z", local_zone), local_zone.tm_zone)
check.eq("numeric and named date forms",
(time.strftime("%Y-%m-%d %H:%M:%S", fields), time.strftime("%a %b %d %H:%M:%S %Y", fields)),
("2024-02-29 15:04:05", "Thu Feb 29 15:04:05 2024"))
text = "Fri Mar 01 09:30:00 2024"
fmt = "%a %b %d %H:%M:%S %Y"
parsed = time.strptime(text, fmt)
check.eq("parse and interpret in local time", time.strftime(fmt, time.localtime(time.mktime(parsed))), text)
check.eq("strptime missing fields use default year and midnight",
tuple(time.strptime("19 Nov", "%d %b"))[:6], (1900, 11, 19, 0, 0, 0))
check.eq("parsed DST is unknown without a zone", parsed.tm_isdst, -1)
check.eq("two digit year pivot", tuple(time.strptime(str(n), "%y").tm_year for n in (68, 69)),
(2068, 1969))
check.eq("12 hour PM input", time.strptime("03 PM", "%I %p").tm_hour, 15)
check.eq("week zero and Sunday weekday", time.strftime("%U %W %w", time.gmtime(1609632000)), "01 00 0")
check.raises("invalid leap date", ValueError, lambda: time.strptime("2023-02-29", "%Y-%m-%d"))
finally:
locale.setlocale(locale.LC_TIME, original)
def inspect_calendar(check):
before = calendar.firstweekday()
check.eq("first weekday defaults to Monday", before, int(calendar.MONDAY))
try:
calendar.setfirstweekday(calendar.SUNDAY)
check.eq("setfirstweekday changes default grid", calendar.firstweekday(), int(calendar.SUNDAY))
check.eq("Sunday grid first row", calendar.monthcalendar(2024, 2)[0], [0, 0, 0, 0, 1, 2, 3])
check.raises("invalid starting weekday", calendar.IllegalWeekdayError, lambda: calendar.setfirstweekday(7))
finally:
calendar.setfirstweekday(before)
grid = calendar.monthcalendar(2024, 2)
check.eq("month grid pads outside days with zero", (grid[0], grid[-1]),
([0, 0, 0, 1, 2, 3, 4], [26, 27, 28, 29, 0, 0, 0]))
check.eq("month grid includes each date once", [day for week in grid for day in week if day], list(range(1, 30)))
check.eq("monthrange and weekday agree", (calendar.monthrange(2024, 2), calendar.weekday(2024, 2, 1)),
((calendar.THURSDAY, 29), calendar.THURSDAY))
check.eq("century leap rules", tuple(calendar.isleap(y) for y in (1900, 2000, 2024, 2100)),
(False, True, True, False))
check.eq("leapdays excludes final year", (calendar.leapdays(2016, 2024), calendar.leapdays(2016, 2025)), (2, 3))
month = calendar.month(2024, 2)
check.eq("text month title, headings and final week",
tuple(month.splitlines()[i].strip() for i in (0, 1, -1)),
("February 2024", "Mo Tu We Th Fr Sa Su", "26 27 28 29"))
year = calendar.calendar(2024, w=3, l=2, c=7, m=2)
check.eq("text year uses two months across", any("January" in line and "February" in line
for line in year.splitlines()), True)
check.eq("two month layout puts March on another line",
any("January" in line and "March" in line for line in year.splitlines()), False)
with StringIO() as stream, redirect_stdout(stream):
calendar.prmonth(2024, 2, w=3, l=2)
calendar.prcal(2024, w=3, l=2, c=7, m=2)
check.eq("print variants match returned calendars",
stream.getvalue(), calendar.month(2024, 2, w=3, l=2) + year)
def main():
check = Checks()
sample = 1709219045
negative_local = inspect_clock(check, sample)
inspect_formats(check, sample)
saved = locale.setlocale(locale.LC_TIME)
try:
locale.setlocale(locale.LC_TIME, "C")
inspect_calendar(check)
finally:
locale.setlocale(locale.LC_TIME, saved)
check.eq("clock removed in this Python", hasattr(time, "clock"), False)
wall_start, cpu_start = time.perf_counter(), time.process_time()
check.eq("sleep returns None", time.sleep(0.04), None)
wall_elapsed, cpu_elapsed = time.perf_counter() - wall_start, time.process_time() - cpu_start
check.eq("sleep contributes to elapsed seconds", wall_elapsed >= 0.035, True)
check.eq("CPU clock during bounded sleep", 0 <= cpu_elapsed < wall_elapsed, True)
cpu_start = time.process_time()
sum(i*i for i in range(1_000_000))
check.eq("CPU clock counts computation", time.process_time() > cpu_start, True)
with StringIO() as stream:
elapsed = progress(stream)
frames = stream.getvalue().strip("\n").split("\r")[1:]
check.eq("progress frames and elapsed counter", [frame.split("]")[0].strip() + "]" for frame in frames],
["0% [....]", "25% [#...]", "50% [##..]", "75% [###.]", "100% [####]"])
check.eq("progress uses carriage returns then final newline",
(stream.getvalue().count("\r"), stream.getvalue().count("\n")), (5, 1))
check.eq("elapsed time advances through pauses",
(elapsed == sorted(elapsed), elapsed[-1] >= 0.035), (True, True))
check.finish("python3-date-time", python=platform.python_version(),
implementation=platform.python_implementation(), platform=platform.platform(),
input_epoch=sample, format_locale="C", local_timezone=time.tzname,
negative_localtime_result=negative_local, has_tzset=hasattr(time, "tzset"),
sleep_seconds=0.04, wall_elapsed=wall_elapsed, cpu_elapsed=cpu_elapsed)
if __name__ == "__main__":
if sys.argv[1:] == ["--progress"]:
progress(sys.stdout)
else:
main()
所需环境:本地 Python 环境
当前源码 SHA256:58c399850debadab14cd775cbb975f24d2b9dcecf81c65866ebda2c2be2df949
当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。
常见错误与边界
- 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。
练习与解答
使用本站实例修改一个条件,先写下预期,再实际运行。
展开参考解答
比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。