我有一个包含时间戳的数据文件,如“1331856000000”。不幸的是,我没有很多关于这种格式的文档,所以我不确定时间戳是如何格式化的。我尝试了Python的标准datetime.fromordinal()和datetime.fromtimestamp()和其他一些方法,但都不匹配。我非常确定这个特定的数字对应于当前的日期(例如2012-3-16),但仅此而已。

如何将此数字转换为日期时间?


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)

这回答了你的问题吗?

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


或者,你也可以使用熊猫。To_datetime并选择自己的单位和时区。这就避免了前面回答中提到的所有评论和问题:

import pandas as pd

pd.to_datetime(int('1331856000000'), utc=True, unit='ms')
# Timestamp('2012-03-16 00:00:00+0000', tz='UTC')

类似于@Tadek的答案

如果时间戳位于UTC时区(一种存储日期的常用方法),则应该使用

datetime.datetime.utcfromtimestamp()

如果你使用fromtimestamp,它会假设日期是用你的本地时区表示的