如何将整数时间戳转换为Python日期时间

问题:如何将整数时间戳转换为Python日期时间

我有一个数据文件,包含“ 1331856000000”之类的时间戳。不幸的是,我没有太多有关该格式的文档,所以我不确定时间戳的格式。我已经尝试了Python的标准datetime.fromordinal()datetime.fromtimestamp()其他一些标准,但是没有任何匹配。我很确定特定数字对应于当前日期(例如2012-3-16),但不多。

如何将此数字转换为datetime

I have a data file containing timestamps like “1331856000000”. Unfortunately, I don’t have a lot of documentation for the format, so I’m not sure how the timestamp is formatted. I’ve tried Python’s standard datetime.fromordinal() and datetime.fromtimestamp() and a few others, but nothing matches. I’m pretty sure that particular number corresponds to the current date (e.g. 2012-3-16), but not much more.

How do I convert this number to a datetime?


回答 0

datetime.datetime.fromtimestamp()是正确的,除了您的时间戳可能以毫秒为单位(例如在JavaScript中),但fromtimestamp()希望Unix时间戳以秒为单位。

那样做:

>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)

结果是:

>>> date
datetime.datetime(2012, 3, 16, 1, 0)

它能回答您的问题吗?

编辑:JF塞巴斯蒂安正确建议使用真司1e3(浮动1000)。如果您想获得精确的结果,则差异非常明显,因此我更改了答案。所不同的结果在Python 2.x中的默认行为,它总是返回int分(当使用/运营商)intint(这就是所谓的地板事业部)。通过更换除数1000(作为一个int与所述)1e3除数(即的表示1000为float)或用float(1000)(或1000.等),分割变得真正分裂。的Python 2.x的收益float除以时int通过floatfloat通过intfloatfloat等而当在传递到时间戳一些小数部分fromtimestamp()的方法,该方法的结果也包含有关该小数部分的信息(如微秒的数量)。

datetime.datetime.fromtimestamp() is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp() expects Unix timestamp, in seconds.

Do it like that:

>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)

and the result is:

>>> date
datetime.datetime(2012, 3, 16, 1, 0)

Does it answer your question?

EDIT: J.F. Sebastian correctly suggested to use true division by 1e3 (float 1000). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int when dividing (using / operator) int by int (this is called floor division). By replacing the divisor 1000 (being an int) with the 1e3 divisor (being representation of 1000 as float) or with float(1000) (or 1000. etc.), the division becomes true division. Python 2.x returns float when dividing int by float, float by int, float by float etc. And when there is some fractional part in the timestamp passed to fromtimestamp() method, this method’s result also contains information about that fractional part (as the number of microseconds).