更新时间:2023-02-03 19:05:00
它是已知的 Python 3.4问题:
>>> from datetime import datetime
>>> local = datetime(2014, 1, 30, 23, 59, 40, 1999)
>>> datetime.fromtimestamp(local.timestamp())
datetime.datetime(2014, 1, 30, 23, 59, 40, 1998)
注意:微秒已消失。 .timestamp()
已经返回的结果略小于 1999
微秒:
Note: the microsecond is gone. The .timestamp()
already returns result that is slightly less than 1999
microseconds:
>>> from decimal import Decimal
>>> local.timestamp()
1391126380.001999
>>> Decimal(local.timestamp())
Decimal('1391126380.0019989013671875')
>>> from datetime import datetime
>>> local = datetime(2014, 1, 30, 23, 59, 40, 1999)
>>> datetime.fromtimestamp(local.timestamp())
datetime.datetime(2014, 1, 30, 23, 59, 40, 1999)
要解决此问题,可以使用显式公式:
To workaround the issue, you could use the explicit formula:
>>> from datetime import datetime, timedelta
>>> local = datetime(2014, 1, 30, 23, 59, 40, 1999)
>>> datetime.utcfromtimestamp(local.timestamp())
datetime.datetime(2014, 1, 30, 23, 59, 40, 1998) # UTC time
>>> datetime(1970, 1, 1) + timedelta(seconds=local.timestamp())
datetime.datetime(2014, 1, 30, 23, 59, 40, 1999) # UTC time
注意:所有示例中的输入均为本地时间,但结果为最后一个的UTC时间。
Note: the input in all examples is the local time but the result is UTC time in the last one.