Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Unix time doesn't work in Javascript

In Python, using calendar.timegm(), I get a 10 digit result for a unix timestamp. When I put this into Javscript's setTime() function, it comes up with a date in 1970. It evidently needs a unix timestamp that is 13 digits long. How can this happen? Are they both counting from the same date?

How can I use the same unix timestamp between these two languages?

In Python:

In [60]: parseddate.utctimetuple()
Out[60]: (2009, 7, 17, 1, 21, 0, 4, 198, 0)
In [61]: calendar.timegm(parseddate.utctimetuple())
Out[61]: 1247793660

In Firebug:

>>> var d = new Date(); d.setTime(1247793660); d.toUTCString()
"Thu, 15 Jan 1970 10:36:55 GMT"
like image 326
rick Avatar asked Jul 03 '09 00:07

rick


People also ask

Does JavaScript use Unix time?

The UNIX timestamp is defined as the number of seconds since January 1, 1970 UTC. In JavaScript, in order to get the current timestamp, you can use Date. now() . It's important to note that Date.

How do I convert UTC time to Unix timestamp in python?

DateTime to Unix timestamp in UTC Timezone In the time module, the timegm function returns a Unix timestamp. The timetuple() function of the datetime class returns the datetime's properties as a named tuple. To obtain the Unix timestamp, use print(UTC).

Are Unix timestamps always UTC?

A few things you should know about Unix timestamps:Unix timestamps are always based on UTC (otherwise known as GMT). It is illogical to think of a Unix timestamp as being in any particular time zone. Unix timestamps do not account for leap seconds.

How do you convert Unix time to normal time in python?

With the help of the fromtimestamp() function, we can convert Unix time to a datetime object in Python.


2 Answers

timegm is based on Unix's gmtime() method, which return seconds since Jan 1, 1970.

Javascripts setTime() method is milliseconds since that date. You'll need to multiply your seconds times 1000 to convert to the format expected by Javascript.

like image 178
Reed Copsey Avatar answered Sep 20 '22 17:09

Reed Copsey


Here are a couple of python methods I use to convert to and from javascript/datetime.

def to_datetime(js_timestamp):
    return  datetime.datetime.fromtimestamp(js_timestamp/1000)

def js_timestamp_from_datetime(dt):
    return 1000 * time.mktime(dt.timetuple())

In javascript you would do:

var dt = new Date();
dt.setTime(js_timestamp);
like image 22
Ben Noland Avatar answered Sep 17 '22 17:09

Ben Noland