简体   繁体   English

在Python中将java System.currentTimeMillis()转换为日期

[英]Converting a java System.currentTimeMillis() to date in python

I have timestamp in milliseconds from 1970. I would like to convert it to a human readable date in python. 我从1970年开始以毫秒为单位的时间戳。我想将它转换为python中的人类可读日期。 I don't might losing some precision if it comes to that. 如果涉及到这一点,我不会失去一些精确度。

How should I do that ? 我该怎么办?

The following give ValueError: timestamp out of range for platform time_t on Linux 32bit 以下为Linux 32bit上的平台time_t的ValueError:timestamp超出范围

#!/usr/bin/env python
from datetime import date
print date.fromtimestamp(1241711346274)

Thank you, Maxim. 谢谢你,马克西姆。

Python expects seconds, so divide it by 1000.0 first: Python需要秒,所以先将它除以1000.0:

>>> print date.fromtimestamp(1241711346274/1000.0)
2009-05-07

You can preserve the precision, because in Python the timestamp is a float. 您可以保留精度,因为在Python中,时间戳是一个浮点数。 Here's an example: 这是一个例子:

import datetime

java_timestamp = 1241959948938
seconds = java_timestamp / 1000
sub_seconds  = (java_timestamp % 1000.0) / 1000.0
date = datetime.datetime.fromtimestamp(seconds + sub_seconds)

You can obviously make it more compact than that, but the above is suitable for typing, a line at a time, in the REPL, so see what it does. 显然你可以使它更紧凑,但上面的内容适合在REPL中一次输入一行,所以看看它的作用。 For example: 例如:

Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) 
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> java_timestamp = 1241959948938
>>> import datetime
>>> seconds = java_timestamp / 1000
>>> seconds
1241959948L
>>> sub_seconds  = (java_timestamp % 1000.0) / 1000.0
>>> sub_seconds
0.93799999999999994
>>> date = datetime.datetime.fromtimestamp(seconds + sub_seconds)
>>> date
datetime.datetime(2009, 5, 10, 8, 52, 28, 938000)
>>> 

它以毫秒为单位将时间戳除以1000,以秒为单位。

date.fromtimestamp(1241711346274/1000)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM