datetime.datetime
的类。
fromtimestamp
它似乎可以工作,除了如果我提供一个timezone
对象。在这种情况下,返回的对象是基类型 datetime
。
import time
from datetime import datetime, timezone
class MyDatetime(datetime):
pass
MyDatetime.fromtimestamp(time.time())
# MyDatetime(2018, 11, 30, 18, 8, 36, 418105)
# <class '__main__.MyDatetime'>
MyDatetime.fromtimestamp(time.time(), tz=timezone.utc)
# datetime.datetime(2018, 11, 30, 17, 8, 50, 667385, tzinfo=datetime.timezone.utc)
# <class 'datetime.datetime'>
这似乎令人惊讶。我在文档中没有看到任何提及这种奇怪行为的内容,是我遗漏了什么还是它是一个 Python bug?
这是设置时区时执行的日期算术运算的副作用。
我不确定这是否是预期的行为
现在它可以正常工作了。
添加了替代选项
ZoneInfo
import time
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
class MyDatetime(datetime):
pass
print('My local time (GMT+5)')
print(type(MyDatetime.fromtimestamp(time.time())))
print(MyDatetime.fromtimestamp(time.time()))
print()
print('Time UTC using timezone')
print(type(MyDatetime.fromtimestamp(time.time(), tz=timezone.utc)))
print(MyDatetime.fromtimestamp(time.time(), tz=timezone.utc))
print()
print('Time UTC using ZoneInfo')
print(type(MyDatetime.fromtimestamp(time.time(), ZoneInfo('UTC'))))
print(MyDatetime.fromtimestamp(time.time(), ZoneInfo('UTC')))
结果:
My local time (GMT+5)
<class '__main__.MyDatetime'>
2024-09-22 22:29:03.734214
Time UTC using timezone
<class '__main__.MyDatetime'>
2024-09-22 17:29:03.734259+00:00
Time UTC using ZoneInfo
<class '__main__.MyDatetime'>
2024-09-22 17:29:03.734683+00:00