views:

1365

answers:

3

Hello,

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.

+1  A: 

It's in milliseconds divided the timestamp by 1000 to become in seconds.

date.fromtimestamp(1241711346274/1000)
Nadia Alramli
+7  A: 

Python expects seconds, so divide it by 1000.0 first:

>>> print date.fromtimestamp(1241711346274/1000.0)
2009-05-07
cartman
Might want to divide by 1000.0 to force floating point in older versions of Python.
S.Lott
Indeed, edited as such. Thanks.
cartman
+2  A: 

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)
>>>
Brian Clapper