本文介绍了如何将整数时间戳转换为 Python 日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如何将此数字转换为 datetime?

解决方案

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

这样做:

>>>导入日期时间>>>your_timestamp = 1331856000000>>>日期 = datetime.datetime.fromtimestamp(your_timestamp/1e3)

结果是:

>>>日期datetime.datetime(2012, 3, 16, 1, 0)

它能回答你的问题吗?

编辑:J.F. 塞巴斯蒂安正确地建议通过 1e3(浮动 1000)使用真正的除法.如果您想获得精确的结果,差异很大,因此我更改了答案.差异源于 Python 2.x 的默认行为,当(使用 / 运算符)int 除以 时,它总是返回 intint(这称为楼层划分).通过用 1e3 除数(将 1000 表示为浮点数)替换除数 1000(作为 int)或使用 float(1000)(或 1000. 等),除法变为 真正的除法.Python 2.x 在将 int 除以 floatfloat 除以 int 时返回 float, 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 日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 19:37