我在 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)
最佳答案
这是一个已知的Python 3.4 issue :
>>> 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
微秒的结果:
>>> from decimal import Decimal
>>> local.timestamp()
1391126380.001999
>>> Decimal(local.timestamp())
Decimal('1391126380.0019989013671875')
The rounding is fixed in the next 3.4, 3.5, 3.6 releases :
>>> 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)
要解决此问题,您可以使用显式公式:
>>> 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时间。
关于python - 将日期时间转换为时间戳并再次转换回来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32767394/