By Jochen Voss, on
For one of my programming experiments, I want to compute timestamps by using the number of seconds since the beginning of 1970. The resulting value will be used for communication between a web browser and my web server. My aim is to find a method to get the very similar values for the timestamp in JavaScript code running on the web browser and in a Python program running on my web server.
To solve this problem, I need a method which does not depend on the time zone the web user is in, and which does not break when the daylight saving time (DST) starts or ends. One solution to this problem is, to perform the computation of the timestamp in Coordinated Universal Time (UTC, a successor of the Greenwich Mean Time). For reference, this post describes what I found.
In the web browser, I am using the following JavaScript code:
now = new Date() timestamp = now.getTime() / 1000
Here, the getTime
method does all the work; since
JavaScript timestamps use milliseconds since the beginning of 1970, we
have to divide by 1000 to convert to seconds. According to the
ECMAScript specification
(also governing JavaScript), the resulting value should be independent of
time zone and DST. For testing, I changed the clock of my computer to a
different time zone; everything still worked: after restarting the
browser, now
reflects the new time zone, but
timestamp
is only changed by the few seconds I needed to
restart the browser.
The code on the web server is written in Python. After a lot of experimenting, I've found two working combinations: The more straightforeward way of computing a timestamp is as follows.
import datetime import time now = datetime.datetime.now() timestamp = time.mktime(now.timetuple()) + now.microsecond * 1e-6
Despite the fact that there is no explicit conversion to UTC in this
code, the computed timestamp gives the number of seconds since the start
of 1970 in UTC. This depends on time.mktime
's ability to
magically know the current time zone of the computer this code is running
on. The same computation can also be done using times in UTC directly.
import datetime import calendar now = datetime.datetime.utcnow() timestamp = calendar.timegm(now.utctimetuple()) + now.microsecond * 1e-6
This time, the code depends on the utcnow
function knowing
the current timezone. An ugly point of the second solution is, that it
requires the slightly obscure
calendar module
from the Python standard library. Again, I tested this code by changing
the time zone of the computer's clock and all worked as expected.
This is an excerpt from Jochen's blog.
Newer entry: Finite Element Discretisation for SPDEs
Older entry: neat trick!
Copyright © 2012 Jochen Voss. All content on this website (including text, pictures, and any other original works), unless otherwise noted, is licensed under the CC BY-SA 4.0 license.