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

运行本章核心实例

PYTHONWindows CPython 3.12, fixed schedule fixtures, C locale and pinned Asia/Shanghai and America/New_York datapython-datetime.py
python-datetime.py147 行
"""Replay the lesson with fixed schedules, real conversions and explicit assertions."""
from datetime import date, datetime, time, timedelta, timezone, tzinfo
import json
import locale
from pathlib import Path
import sys
from warnings import catch_warnings, simplefilter
from zoneinfo import ZoneInfo, reset_tzpath


def main():
    if len(sys.argv) == 2:
        wheel = Path(sys.argv[1]).resolve(strict=True)
        sys.path.insert(0, str(wheel))
        reset_tzpath(())
    elif len(sys.argv) > 2:
        raise SystemExit("usage: python python-datetime.py [local-tzdata-wheel]")
    checks = []

    def check(name, actual, expected, inputs, operation):
        if actual != expected:
            raise AssertionError((name, actual, expected))
        checks.append(dict(name=name, inputs=inputs, operation=operation, actual=actual,
                           expected=expected, passed=True))

    def rejects(name, error, operation, inputs):
        try:
            operation()
        except error as raised:
            check(name, type(raised).__name__, error.__name__, inputs, 'Call the constructor or parser')
        else:
            raise AssertionError(name)

    day = date(2024, 9, 3)
    clock = time(7, 5, 6, 840)
    shift = datetime(2024, 2, 28, 23, 40, 5)
    utc = timezone.utc
    check('date constructor and fields', [day.year, day.month, day.day], [2024, 9, 3],
          [2024, 9, 3], 'Construct a date and read its three fields')
    check('time constructor and fields', [clock.hour, clock.minute, clock.second, clock.microsecond],
          [7, 5, 6, 840], [7, 5, 6, 840], 'Read the four time fields')
    check('datetime constructor', [shift.year, shift.isoformat(' ')], [2024, '2024-02-28 23:40:05'],
          [2024, 2, 28, 23, 40, 5], 'Construct a date and time together')
    check('timezone concrete tzinfo', [isinstance(utc, tzinfo), utc.utcoffset(None).total_seconds()],
          [True, 0.0], 'timezone.utc', 'Inspect the concrete UTC implementation')
    before = datetime.now()
    today = date.today()
    after = datetime.now()
    check('today matches local clock', today in (before.date(), after.date()), True,
          'System clock without adjustment during adjacent calls', 'Read local dates around date.today()')
    check('date ISO accepted inputs',
          [date.fromisoformat(value).isoformat() for value in ('2024-09-03', '20240903', '2024-W36-2')],
          ['2024-09-03'] * 3, ['2024-09-03', '20240903', '2024-W36-2'], 'Parse calendar and week dates')
    check('weekday Monday and Sunday', [date(2024, 9, 2).weekday(), date(2024, 9, 8).weekday()], [0, 6],
          ['2024-09-02', '2024-09-08'], 'Read weekday numbers at the two endpoints')
    check('date ISO output', day.isoformat(), '2024-09-03', '3 September 2024', 'Format the date as ISO text')
    check('date custom formatting', day.strftime('%Y/%m/%d'), '2024/09/03', '%Y/%m/%d', 'Format the same date')
    check('time ISO precision and offset',
          [clock.isoformat(), time(7, 5, 6).isoformat(),
           clock.replace(tzinfo=utc).isoformat(timespec='seconds')],
          ['07:05:06.000840', '07:05:06', '07:05:06+00:00'],
          '07:05:06 with microseconds 840 or 0, plus a UTC case', 'Compare three ISO time strings')
    check('time custom formatting', clock.strftime('%H:%M'), '07:05', '%H:%M', 'Select hour and minute')
    check('current local and aware UTC',
          [before.tzinfo is None, datetime.now(utc).utcoffset().total_seconds()], [True, 0.0],
          'System local clock and UTC', 'Read now() with and without an explicit time zone')
    with catch_warnings(record=True) as notices:
        simplefilter('always', DeprecationWarning)
        historical = datetime.utcnow()
    check('legacy utcnow is naive and deprecated',
          [historical.tzinfo is None, any(w.category is DeprecationWarning for w in notices)], [True, True],
          'CPython 3.12 with a warning filter', 'Call the legacy API and record the warning category')
    stamp = 1_704_067_200.25
    actual_utc = datetime.fromtimestamp(stamp, tz=utc)
    actual_local = datetime.fromtimestamp(stamp)
    check('timestamp explicit UTC and local', [actual_utc.isoformat(), actual_local.tzinfo is None],
          ['2024-01-01T00:00:00.250000+00:00', True], stamp, 'Construct explicit UTC and system-local values')
    check('timestamp round trip', [actual_utc.timestamp(), actual_local.timestamp()], [stamp, stamp],
          stamp, 'Convert both datetime representations back to POSIX seconds')
    zoned = shift.replace(tzinfo=utc)
    check('datetime date and time projections',
          [zoned.date().isoformat(), zoned.time().isoformat(), zoned.timetz().isoformat()],
          ['2024-02-28', '23:40:05', '23:40:05+00:00'], zoned.isoformat(), 'Extract date, time and timetz')
    check('datetime custom formatting', shift.strftime('%Y-%m-%d %H:%M:%S'), '2024-02-28 23:40:05',
          shift.isoformat(), 'Render date and clock together')
    negative = timedelta(microseconds=-1)
    check('negative delta components',
          [negative.days, negative.seconds, negative.microseconds,
           negative.total_seconds()], [-1, 86399, 999999, -0.000001], '-1 microsecond',
          'Inspect normalized day, second and microsecond fields plus total_seconds')
    directed = datetime.combine(day, clock)
    digits = ['%Y', '%m', '%d', '%H', '%M', '%S']
    check('numeric directives separately', [directed.strftime(token) for token in digits],
          ['2024', '09', '03', '07', '05', '06'], digits, 'Format each directive independently')
    previous_locale = locale.setlocale(locale.LC_TIME)
    try:
        locale.setlocale(locale.LC_TIME, 'C')
        words = ['%A', '%a', '%B', '%b']
        check('locale name directives separately', [directed.strftime(token) for token in words],
              ['Tuesday', 'Tue', 'September', 'Sep'], dict(locale='C', tokens=words),
              'Format each name independently in the C locale')
    finally:
        locale.setlocale(locale.LC_TIME, previous_locale)
    check('datetime plus ten days', (shift + timedelta(days=10)).isoformat(), '2024-03-09T23:40:05',
          shift.isoformat(), 'Add ten days across February in a leap year')
    check('datetime plus days and hours', (shift + timedelta(days=3, hours=2)).isoformat(),
          '2024-03-03T01:40:05', shift.isoformat(), 'Add three days and two hours across midnight and month')
    first, last = date(2024, 2, 27), date(2024, 3, 2)
    check('signed date difference', [(last-first).days, (first-last).days], [4, -4],
          [first.isoformat(), last.isoformat()], 'Subtract the two dates in both orders')
    check('parse a scheduled string',
          datetime.strptime('2024/02/29 07:05', '%Y/%m/%d %H:%M').isoformat(), '2024-02-29T07:05:00',
          '2024/02/29 07:05', 'Parse with explicit numeric directives')
    rejects('invalid calendar date', ValueError, lambda: date(2024, 2, 30), '2024-02-30')
    rejects('invalid parse pattern', ValueError,
            lambda: datetime.strptime('2024-02-29', '%d/%m/%Y'), '2024-02-29 with %d/%m/%Y')
    check('replace makes a new value', [shift.hour, shift.replace(hour=10).hour], [23, 10],
          shift.isoformat(), 'Replace the hour and re-read the original')
    shanghai = ZoneInfo('Asia/Shanghai')
    shanghai_now = datetime.now(shanghai)
    check('current Shanghai time is aware', [shanghai_now.tzinfo.key, shanghai_now.utcoffset().total_seconds()],
          ['Asia/Shanghai', 28800.0], 'Current clock, IANA Asia/Shanghai', 'Read current regional time and offset')
    fixed = timezone(timedelta(hours=8))
    local = actual_utc.astimezone(shanghai)
    check('Shanghai conversion preserves instant',
          [local.isoformat(), local.timestamp(), actual_utc.astimezone(fixed).isoformat()],
          ['2024-01-01T08:00:00.250000+08:00', stamp, '2024-01-01T08:00:00.250000+08:00'],
          actual_utc.isoformat(), 'Convert the instant using IANA data and a fixed +08:00 offset')
    check('replace is not zone conversion', actual_utc.replace(tzinfo=fixed).timestamp(), stamp - 28800,
          actual_utc.isoformat(), 'Reinterpret the same wall fields and compare timestamps')
    nyc = ZoneInfo('America/New_York')
    instants = [datetime(2024, 11, 3, hour, 30, tzinfo=utc) for hour in (5, 6)]
    repeated = [instant.astimezone(nyc) for instant in instants]
    check('New York repeated hour has two folds',
          [[item.isoformat(), item.fold] for item in repeated],
          [['2024-11-03T01:30:00-04:00', 0], ['2024-11-03T01:30:00-05:00', 1]],
          [instant.isoformat() for instant in instants], 'Convert two UTC instants to a repeated local hour')
    check('UTC subtraction gives elapsed time across fold',
          [(repeated[1] - repeated[0]).total_seconds(),
           (repeated[1].astimezone(utc) - repeated[0].astimezone(utc)).total_seconds()], [0.0, 3600.0],
          [item.isoformat() for item in repeated], 'Compare wall-clock and UTC subtraction')
    print(json.dumps(checks, ensure_ascii=False))


if __name__ == '__main__':
    main()
本例需在 Windows CPython 3.12, fixed schedule fixtures, C locale and pinned Asia/Shanghai and America/New_York data 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows CPython 3.12, fixed schedule fixtures, C locale and pinned Asia/Shanghai and America/New_York data

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

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

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip

下载课程关联工程包:Python

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a294.zip

下载课程关联工程包:Python

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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