I have timestamp in milliseconds from 1970. I would like to convert it to a human readable date in 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
#!/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:
>>> print date.fromtimestamp(1241711346274/1000.0)
2009-05-07
You can preserve the precision, because in Python the timestamp is a float. 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. 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)
>>>
It's in milliseconds divided the timestamp by 1000 to become in seconds.
date.fromtimestamp(1241711346274/1000)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With