蓝色天空网mbsky.com · 知识 · 实践 · 创造Python · 本地阅读预览
教程 / Python / 数据科学 / Python

Python datetime:日历日期、时间间隔与时区

用固定的排班数据核对日期加减、字符串转换和 UTC 与当地时间的关系。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

先选日期、时刻还是时间间隔

date 表示日历上的某一天,time 表示一天中的钟表读数。把年月日和时分秒放在一起用 datetime。用 timedelta 表示两个日期或日期时间之差,也可用它从一个已知日期推算另一个日期。单独的 time 没有日期,因此跨午夜运算应先构造 datetime。

直接用构造函数记录计划时刻,例如 datetime(2024, 2, 28, 23, 40, 5)。date.today() 读取机器的本地日期,datetime.now() 读取本地日期时间,实际结果随系统时钟变化。创建时会检查日历和钟表字段,2 月 30 日触发 ValueError。

日期、时间、日期时间和间隔值都不可变。replace 返回新值,原先记录可继续使用。若程序确有反复转换同一值的开销,可先测量,再决定缓存范围。

格式化给人看,解析给程序用

用 strftime 把值转为文本。%Y-%m-%d %H:%M:%S 固定数字字段顺序,%M 是分钟,%m 是月份。星期和月份名称按 LC_TIME 区域设置变化。实验在 C 区域核对 September、Sep、Tuesday 和 Tue。

用 datetime.strptime(text, format) 按匹配的格式解析。例如排班输入 2024/02/29 07:05 对应 %Y/%m/%d %H:%M,得到 2024 年 2 月 29 日 07:05。格式或日期无效时触发 ValueError。解析字符串前应明确其时区语义。

机器间交换可使用 ISO 日期或日期时间文本。date.isoformat() 输出 YYYY-MM-DD。Python 3.11 起,date.fromisoformat() 也接受如 20240903 或 2024-W36-2 的形式。time.isoformat() 默认省略为零的微秒,带偏移的 time 可输出偏移,也可通过 timespec 指定精度。

跨月计算与负间隔

两个 date 相减会得到 timedelta。2024 年 3 月 2 日减去 2 月 27 日是 4 天,逆序是负 4 天。对 datetime 可同时加天和小时,例如 2024 年 2 月 28 日 23:40 加 3 天 2 小时得到 3 月 3 日 01:40。

timedelta 的 days 可为负,seconds 和 microseconds 是规范化后的日内余量。负一微秒拆成 -1 天、86399 秒和 999999 微秒。要取得完整秒数,用 total_seconds(),只取 seconds 会漏掉整天。

这些例子按日历和墙钟字段计算。需要核对跨夏令时的实际经过秒数时,先将两个时刻转为 UTC 再相减。

明确 UTC、固定偏移和地区规则

标准库的 tzinfo 提供时区接口,timezone.utc 和 timezone(timedelta(hours=8)) 适用于固定偏移。按地区规则转换时使用 Python 3.9 起的 ZoneInfo。它需要系统 IANA 数据或安装 tzdata,尤其是 Windows 上的环境。

保留 UTC 的写法是 datetime.now(timezone.utc),传给 astimezone(ZoneInfo("Asia/Shanghai")) 可得到同一时刻的上海钟表读数。历史代码可能使用 pytz 并通过 utcnow().replace(tzinfo=pytz.utc) 附上时区。utcnow() 返回没有时区信息的值,自 Python 3.12 起弃用。replace(tzinfo=...) 只改解释,astimezone() 会转换显示读数。

同一条 POSIX 时间戳可按系统本地时间或显式指定的时区解释。用 datetime.fromtimestamp(ts, tz=timezone.utc) 得到带时区的 UTC 值,再用 timestamp() 转回秒数。旧 utcfromtimestamp() 也自 3.12 起弃用。不要依赖本地配置来解释跨机器传递的时间戳。

地区规则可能让一个当地钟表读数出现两次。纽约 2024 年秋季回拨时,05:30 UTC 和 06:30 UTC 都显示为 01:30,偏移分别为 -04:00 和 -05:00。由 UTC 转换时,ZoneInfo 会标记 fold 为 0 或 1。这里仅核对指定地区和日期。

下载后复跑排班实验

解压后在实验目录执行 python python-datetime.py。实验使用系统 IANA 时区数据或预先安装的 tzdata,按固定排班、负间隔、格式、时间戳和地区转换逐项输出输入、操作、预期与实际结果。涉及当前时钟的用例检查相邻读取是否一致。

下载本站 datetime 实验 ZIP

所需环境:CPython 3.12 与 IANA 时区数据

ZIP SHA256:72d65dfb5192312c3ee97a296607680545a8b606edbdeac55a67e1dad81e6e58

核心类型

成员、方法或符号作用和条件
date(year, month, day)保存公历年、月、日,构造时检查日期。
time(hour=0, minute=0, second=0, microsecond=0, …)保存一天中的时分秒和微秒,可选偏移信息。
datetime(year, month, day, …)合在同一个对象中表示日期和日内时刻,可携带时区。
timedelta(…, days=0, seconds=0, microseconds=0, …)保存有符号时间间隔,支持加减。
tzinfo时区接口的基类。由具体实现给出偏移、名称和夏令时规则。

日期对象

成员、方法或符号作用和条件
date.today()根据当前机器的本地时钟返回日期。
date.fromisoformat(text)按支持的 ISO 日期形式解析文本,3.11 起也接受紧凑及周日期。
date.year只读的年份字段。
date.month只读的月份字段,从 1 到 12。
date.day只读的月内日期,上限随月份和闰年变化。
date.weekday()星期一为 0,星期日为 6。
date.isoformat()把日期输出为 YYYY-MM-DD。
date.strftime(format)按格式指令渲染日期。

钟表对象

成员、方法或符号作用和条件
time.hour只读小时,从 0 到 23。
time.minute只读分钟,从 0 到 59。
time.second只读秒,从 0 到 59。
time.microsecond只读微秒,从 0 到 999999。
time.isoformat(timespec="auto")默认按是否含微秒决定小数部分,有偏移时也输出偏移。
time.strftime(format)按格式指令渲染时分秒。

日期时间对象

成员、方法或符号作用和条件
datetime.now(tz=None)省略时区时取得不带时区信息的本地日期时间,传时区则按该时区返回。
datetime.utcnow()旧接口返回不带时区信息的 UTC 字段,3.12 起弃用,改用 now(timezone.utc)。
datetime.fromtimestamp(ts, tz=None)从 POSIX 秒数构造,默认按本地解释,指定时区可控制表示方式。
datetime.timestamp()返回浮点 POSIX 秒数,未带时区的值按系统本地时间解释。
datetime.date()取出年月日,返回独立的 date。
datetime.time()取出钟表字段,返回不带时区信息的 time。需保留时区时用 timetz()。
datetime.year只读年份字段。
datetime.strftime(format)用指定指令把日期时间转换成显示文本。

间隔字段

成员、方法或符号作用和条件
timedelta.days规范化后的天数,可为负。
timedelta.seconds除去 days 后的秒数余量,范围 0 至 86399。
timedelta.microseconds除去整秒后的微秒余量,范围 0 至 999999。

格式指令

成员、方法或符号作用和条件
%Y输出完整年份,例如 2024。
%m输出两位月份,例如 09。
%d输出两位月内日期,例如 03。
%H输出两位 24 小时制小时,例如 07。
%M输出两位分钟,例如 05。
%S输出两位秒,例如 06。
%A输出当前区域设置下的完整星期名。
%a输出当前区域设置下的缩写星期名。
%B输出当前区域设置下的完整月份名。
%b输出当前区域设置下的缩写月份名。

本章自编源码与运行范围

Python · 阅读源码
"""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

当前源码 SHA256:a4e746ef1260960c62195c4b5fe502b56aa972d5e59a6b42359ea11d7c6b89ba

下载本站示例源码

当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。

常见错误与边界

  • 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。

练习与解答

使用本站实例修改一个条件,先写下预期,再实际运行。

展开参考解答

比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。

规范与官方依据