将日期时间转换为时间戳然后再次返回 [英] Converting datetimes to timestamps and back again

查看:120
本文介绍了将日期时间转换为时间戳然后再次返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python中使用日期时间遇到了一些麻烦。我尝试将日期时间转换为时间戳,然后再次返回,无论我如何尝试最终结果都不一样。我总是以datetime结束(2014、1、30、23、59、40、1998)。

I'm having some trouble with datetime in Python. I tried converting a datetime to a timestamp and then back again and no matter how I try the end result is not the same. I always end up with a datetime of 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问题

>>> 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')

在下一个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)

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

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.

这篇关于将日期时间转换为时间戳然后再次返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆