为何datetime.datetime.strptime的%Z格式不生成时区感知对象?
Python datetime.strptime中%Z格式的行为疑问
先看实际测试结果:
$ python Python 3.13.2 (main, Feb 5 2025, 08:05:21) [GCC 14.2.1 20250128] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import datetime >>> datetime.datetime.strptime("2025-UTC", "%Y-%Z") datetime.datetime(2025, 1, 1, 0, 0) >>> datetime.datetime.strptime("2025-+0000", "%Y-%z") datetime.datetime(2025, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)
根据Python官方文档描述,strptime的%Z格式码仅接受特定值:系统区域设置中time.tzname的任意值,以及硬编码的UTC和GMT。按此描述,使用%Z解析时区信息时,应该返回时区感知的datetime对象,但实际调用结果却返回了无时区信息的naive对象。
奇怪的是,datetime.datetime.strptime调用的底层函数_strptime已经正确解析出了UTC时区:
>>> from _strptime import _strptime >>> _strptime("2025-UTC", "%Y-%Z") ((2025, 1, 1, 0, 0, 0, 2, 1, 0, 'UTC', None), 0, 0)
这个现象在Python 3.5、3.7、3.10、3.12、3.13版本中均存在,推测这是设计特性而非Bug。那么:
%Z在datetime.datetime.strptime中的预期用途和行为到底是什么?- 官方文档的描述是否存在遗漏或模糊之处?
内容的提问来源于stack exchange,提问作者ctmbl
相关产品推荐
相关产品推荐

