Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript timestamp to Python datetime conversion

To get timestamp in JavaScript we use

var ts = new Date().getTime() 

What is the proper way to convert it to a Python datetime so far I use the following code

>>> jsts = 1335205804950 >>> dt = datetime.datetime.fromtimestamp(jsts/1000) >>> dt datetime.datetime(2012, 4, 24, 0, 30, 4) 

I divide timestamp by 1000 because I get error like

ValueError                                Traceback (most recent call last) 1 d = datetime.datetime.fromtimestamp(a) ValueError: year is out of range 

Sultan.

like image 775
sultan Avatar asked Apr 23 '12 18:04

sultan


People also ask

How do I convert a timestamp to a date in Python?

You can simply use the fromtimestamp function from the DateTime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the corresponding DateTime object to timestamp.

How do you convert timestamps to minutes in Python?

Method 1: Use of pandas. Timestamp. minute attribute. This attribute of pandas can be used to extract the minutes from a given timestamp object.

What is Fromtimestamp in Python?

The fromtimestamp() function is used to return the date associated with a given timestamp. The date class's function fromtimestamp() computes and returns the date and time corresponding to a specified timestamp. The timestamps in this example range from 1970 to 2038.


2 Answers

Your current method is correct, dividing by 1000 is necessary because your JavaScript returns the timestamp in milliseconds, and datetime.datetime.fromtimestamp() expects a timestamp in seconds.

To preserve the millisecond accuracy you can divide by 1000.0, so you are using float division instead of integer division:

>>> dt = datetime.datetime.fromtimestamp(jsts/1000.0) >>> dt datetime.datetime(2012, 4, 23, 11, 30, 4, 950000) 
like image 76
Andrew Clark Avatar answered Sep 19 '22 10:09

Andrew Clark


I've had the same issue, thanks to @andrew-clark for the answer, i've build a small example to handle both cases:

     try:         # when timestamp is in seconds         date = datetime.fromtimestamp(timestamp)     except (ValueError):         # when timestamp is in miliseconds         date = datetime.fromtimestamp(timestamp / 1000) 
like image 38
shiny Avatar answered Sep 19 '22 10:09

shiny