"""蓝色天空网 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 环境 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地 Python 环境
入口文件:projects/python-lab/python3-date-time.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
python3-date-time.py,或下载右侧课程工程包。 - 确认本地已准备 本地 Python 环境。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip