如何将整数时间戳转换为Python datetime [英] How to convert integer timestamp to Python datetime
问题描述
datetime.fromordinal()
和 datetime.fromtimestamp()
等几个,但没有火柴。我很确定特定的数字对应于当前日期(例如2012-3-16),但不会太多。 如何将此数字转换为 datetime
?
datetime.datetime。 fromtimestamp()
是正确的,除了你可能有一个毫秒的时间戳(像在JavaScript中),但 fromtimestamp()
期望Unix时间戳,以秒为单位
这样做:
>> ; import datetime
>>>> your_timestamp = 1331856000000
>>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)
,结果是:
>>>日期
datetime.datetime(2012,3,16,1,0)
是否回答你的问题?
编辑:JF Sebastian正确地建议使用真正的区分通过 1e3
(float 1000
)。差异很大,如果你想得到精确的结果,我改变了我的答案。差异来自Python 2.x的默认行为,它在分割时(使用 /
运算符)始终返回 int
int
by int
(这称为 floor division )。通过用 1e3 $ c $(代替
(或 int
)替换除数 1000
c>除数(表示为 1000
为浮点数)或$ code> float(1000) 1000。
等),分区成为真正的划分。在分开 int
的时候,Python 2.x返回 float
float , float
by int
, float
by float
等。当时间戳中有一些小数部分传递给 fromtimestamp()
方法时,此方法的结果还包含有关小数部分(微秒数)。
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
?
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).
这篇关于如何将整数时间戳转换为Python datetime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!