蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行时间戳、格式化和日历边界

PYTHONPython 3.12 / Windowslegacy-datetime-lab.py
legacy-datetime-lab.py145 行
import json


def report(name, value):
    print(json.dumps([name, value], ensure_ascii=True))


def error_name(action):
    try:
        action()
    except (AttributeError, IndexError, KeyError, NameError, TypeError, ValueError) as error:
        return type(error).__name__
    return None


import calendar
import locale
import time
from contextlib import redirect_stdout
from datetime import datetime, timezone
from io import StringIO


locale.setlocale(locale.LC_TIME, "C")
stamp = 1709297445
utc = time.gmtime(stamp)
local = time.localtime(stamp)
fields = ("tm_year", "tm_mon", "tm_mday", "tm_hour", "tm_min", "tm_sec",
          "tm_wday", "tm_yday", "tm_isdst")
report("fields_by_index", dict(zip(fields, utc)))
report("fields_by_name", {name: getattr(utc, name) for name in fields})

now = time.time()
near_ns = time.time_ns()
report("wall_clock", [type(now).__name__, type(near_ns).__name__,
                      abs(now-near_ns/1_000_000_000) < 1])
aware_local = datetime.fromtimestamp(stamp, timezone.utc).astimezone()
report("local_conversion", [list(local), aware_local.isoformat(), time.mktime(local)])
report("asctime_sample", time.asctime(utc))
numeric_format = "%Y-%m-%d %H:%M:%S"
named_format = "%a %b %d %H:%M:%S %Y"
formatted = time.strftime(numeric_format, utc)
parsed = time.strptime(formatted, numeric_format)
default_format_parsed = time.strptime(time.asctime(utc))
report("formatted_roundtrip", [formatted, time.strftime(named_format, utc),
                               calendar.timegm(parsed), calendar.timegm(default_format_parsed),
                               time.mktime(time.strptime(time.strftime(numeric_format, local), numeric_format))])

def negative_local():
    try:
        return list(time.localtime(-1))
    except (OSError, OverflowError, ValueError) as error:
        return type(error).__name__


elapsed_start = time.perf_counter()
cpu_start = time.process_time()
time.sleep(0.02)
elapsed = time.perf_counter() - elapsed_start
cpu = time.process_time() - cpu_start
daylight_hint = (*local[:8], -1)
report("time_api", {
    "time.altzone": [type(time.altzone).__name__, time.altzone, time.daylight],
    "time.asctime": [time.asctime(utc), "\n" in time.asctime(utc)],
    "time.clock": [hasattr(time, "clock"), cpu >= 0, elapsed > 0],
    "time.ctime": [time.ctime(stamp), time.ctime(stamp) == time.asctime(local)],
    "time.gmtime": [list(time.gmtime(0)), list(time.gmtime(-1)), list(time.gmtime(2147483648))],
    "time.localtime": [tuple(local[:6]) == aware_local.timetuple()[:6], local.tm_isdst,
                       negative_local(), list(time.localtime(2147483648))[:6]],
    "time.mktime": [time.mktime(local), time.mktime(daylight_hint), calendar.timegm(utc)],
    "time.sleep": [elapsed >= 0.019, cpu >= 0],
    "time.strftime": [formatted, time.strftime("%Y-%m-%d", utc)],
    "time.strptime": [list(parsed), default_format_parsed[:6],
                      error_name(lambda: time.strptime("2024-02-30", "%Y-%m-%d"))],
    "time.time": [type(now).__name__, abs(now-near_ns/1_000_000_000) < 1],
    "time.tzset": [hasattr(time, "tzset"), "Unix-specific execution not measured"],
})
report("zone_fields", {
    "time.timezone": [time.timezone, int(-aware_local.utcoffset().total_seconds())],
    "time.tzname": [type(time.tzname).__name__, len(time.tzname),
                    all(isinstance(name, str) for name in time.tzname), time.tzname],
})
first_day = time.strptime("2024-01-01", "%Y-%m-%d")
seconds = datetime(2024, 3, 1, 12, 50, 45, tzinfo=timezone.utc)
report("formats", {
    "%y": [time.strftime("%y", utc), time.strptime("68","%y").tm_year, time.strptime("69","%y").tm_year],
    "%Y": time.strftime("%Y", utc),
    "%m": time.strftime("%m", utc),
    "%d": [time.strftime("%d", utc), error_name(lambda: time.strptime("2024-03-00", "%Y-%m-%d"))],
    "%H": time.strftime("%H", utc),
    "%I": [time.strftime("%I", utc), time.strptime("12 AM", "%I %p").tm_hour,
           time.strptime("12 PM", "%I %p").tm_hour],
    "%M": time.strftime("%M", utc),
    "%S": [time.strftime("%S", utc), time.strptime("23:59:60", "%H:%M:%S").tm_sec,
           error_name(lambda: datetime(2024, 1, 1, 23, 59, 60))],
    "%a": time.strftime("%a", utc), "%A": time.strftime("%A", utc),
    "%b": time.strftime("%b", utc), "%B": time.strftime("%B", utc),
    "%c": time.strftime("%c", utc), "%j": time.strftime("%j", utc),
    "%p": [time.strftime("%p", utc), time.strptime("12 AM", "%H %p").tm_hour],
    "%U": [time.strftime("%U", utc), time.strftime("%U", first_day)],
    "%w": time.strftime("%w", utc),
    "%W": [time.strftime("%W", utc), time.strftime("%W", first_day)],
    "%x": time.strftime("%x", utc), "%X": time.strftime("%X", utc),
    "%Z": [seconds.strftime("%Z"), time.strftime("%Z", local)],
    "%%": time.strftime("%%", utc),
})

leaps = [calendar.isleap(year) for year in (2024, 2100, 2400)]
report("leap_rules", leaps)
month = calendar.month(2024, 2)
wider_month = calendar.month(2024, 2, w=3, l=2)
report("month_display", [month.splitlines()[0].strip(), month.splitlines()[1], month.splitlines()[-1].split()])
full_year = calendar.calendar(2024)
two_months = calendar.calendar(2024, m=2)
year_print = StringIO()
month_print = StringIO()
with redirect_stdout(year_print):
    prcal = calendar.prcal(2024)
with redirect_stdout(month_print):
    prmonth = calendar.prmonth(2024, 2)
monday_grid = calendar.monthcalendar(2024, 2)
original_first_weekday = calendar.firstweekday()
try:
    calendar.setfirstweekday(calendar.SUNDAY)
    sunday = calendar.firstweekday()
    sunday_grid = calendar.monthcalendar(2024, 2)
    bad_weekday = error_name(lambda: calendar.setfirstweekday(7))
finally:
    calendar.setfirstweekday(original_first_weekday)
report("calendar_api", {
    "calendar.calendar": [full_year.splitlines()[2].split(), two_months.splitlines()[2].split()],
    "calendar.firstweekday": [original_first_weekday, sunday],
    "calendar.isleap": leaps,
    "calendar.leapdays": [calendar.leapdays(1996, 2004), calendar.leapdays(2000, 2000)],
    "calendar.month": [month.splitlines()[-1].split(), wider_month.splitlines()[1:4]],
    "calendar.monthcalendar": [monday_grid[0], monday_grid[-1], sunday_grid[0]],
    "calendar.monthrange": list(calendar.monthrange(2024, 2)),
    "calendar.prcal": [prcal, year_print.getvalue() == full_year],
    "calendar.prmonth": [prmonth, month_print.getvalue() == month],
    "calendar.setfirstweekday": [sunday, sunday_grid[0][0], bad_weekday, calendar.firstweekday()],
    "calendar.timegm": [calendar.timegm(utc), calendar.timegm(time.gmtime(-1))],
    "calendar.weekday": [calendar.weekday(2024, 2, 29),
                         error_name(lambda: calendar.weekday(2023, 2, 29))],
})
本例需在 Python 3.12 / Windows 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Python 3.12 / Windows

入口文件:projects/python-legacy-lab/legacy-datetime-lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 legacy-datetime-lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 Python 3.12 / Windows。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Python2.x

课程关联工程包(登记关联44章) · 含当前章节或实例 · mbskycom202611a446.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习