将日期时间转换为时间戳并再次转换回来

kjo*_*son 5 python datetime python-3.x

我在 Python 中的日期时间方面遇到了一些问题。我尝试将日期时间转换为时间戳,然后再转换回来,无论我如何尝试,最终结果都不一样。我总是以 datetime(2014, 1, 30, 23, 59, 40, 1998) 的日期时间结束。

import datetime

a = datetime.datetime.timestamp(datetime.datetime(2014, 1, 30, 23, 59, 40, 1999))
b = datetime.datetime.fromtimestamp(a)

print(b)
Run Code Online (Sandbox Code Playgroud)

jfs*_*jfs 4

这是一个已知的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)
Run Code Online (Sandbox Code Playgroud)

注意:微秒消失了。.timestamp()已经返回略小于微秒的结果1999

>>> from decimal import Decimal
>>> local.timestamp()
1391126380.001999
>>> Decimal(local.timestamp())
Decimal('1391126380.0019989013671875')
Run Code Online (Sandbox Code Playgroud)

在接下来的 3.4、3.5、3.6 版本中修复了舍入问题

>>> 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)
Run Code Online (Sandbox Code Playgroud)

要解决此问题,您可以使用显式公式:

>>> 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
Run Code Online (Sandbox Code Playgroud)

注意:所有示例中的输入均为当地时间,但最后一个示例的结果为 UTC 时间。