dijiri dijiri - 1 year ago 88
Javascript Question

Equivalent code in python (time)

Javascript code:

var date = new Date(1466278504960);

return: Sat Jun 18 2016 20:35:04 GMT+0100 (WEST)

How can I convert the same number to date in python ?

When I use

datetime.datetime.fromtimestamp(int("1466278504960")).strftime('%Y-%m-%d %H:%M:%S'))

I receive this error: ValueError: year is out of range

Answer Source

datetime.datetime.fromtimestamp will do this, but you need to divide the value by 1000 first (the numeric value you give and JavaScript's Date expects is in milliseconds since the epoch, where Python's API takes a floating point seconds since the epoch):

from datetime import datetime

date = datetime.fromtimestamp(1466278504960 / 1000.)

That makes the raw datetime object; if you want it formatted the same, you should take a look at datetime object's strftime method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download