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"
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.
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).
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.
With the help of the fromtimestamp() function, we can convert Unix time to a datetime object in Python.
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.
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);
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