By Jochen Voss, on
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.
now = new Date() timestamp = now.getTime() / 1000
getTime method does all the work; since
have to divide by 1000 to convert to seconds. According to the
time zone and DST. For testing, I changed the clock of my computer to a
different time zone; everything still worked: after restarting the
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
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 a Creative Commons Attribution-Share Alike 3.0 License.