News for hackers. Stuff that matters.
Re:Dealing with Timezones in Python by nikcub on Friday July 15, 2011 @07:36AM (#2767021)
a few more gotcha's:

* when storing a UTC timestamp and you need to get a datetime object back in order to add dates or do some calcualtions, make sure you use datetime.datetime.utcfromtimestamp(), eg.

    >>> datetime.datetime.utcfromtimestamp(1310727758.472)
    datetime.datetime(2011, 7, 15, 11, 2, 38, 472000)
* python timestamps are longs and represent time in seconds. in Javascript it is the number of milliseconds since epoch, so you need to divide/multiple by 1000 depending on which way you are going. for eg.

    > new Date().valueOf()
    1310728084389

    >>> datetime.datetime.utcfromtimestamp(1310728084389)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: year is out of range
    >>> datetime.datetime.utcfromtimestamp(1310728084389 / 1000)
    datetime.datetime(2011, 7, 15, 11, 8, 4)
* always set your server to UTC, always use the utc* functions (eg. utctimetuple, utcfromtimestamp, utctime etc.), store as a long, and when passing back to the client send the current UTC timestamp as well rather than relying on the client system clock, which is frequently wrong. You can also use:

http://json-time.appspot.com/time.json?tz=UTC

or implement something similar. I resorted to always outputting the current UTC time into a javascript variable and using that to calibrate the local computer time (again, never trusting client time)

* never use time.time() to get a timestamp back because it will munge the value and re-add tz info

* in Javascript, to go from your server-provided UTC timestamp to a local date object that you can then work with, use:

    > new Date(1310728084 * 1000).toUTCString()
    "Fri, 15 Jul 2011 11:08:04 GMT"
* If you are providing an API or a feed, please include a UTC timestamp in the output - parsing all the different date formats and timestamp info and attempting to work out when something happen (such as when a post was published) is a real pain in the ass. store the timezone in a sep field called 'utc_offset' or similar
Re:Dealing with Timezones in Python by teh on Friday July 15, 2011 @09:39AM (#2767302)
> * never use time.time() to get a timestamp back because it will munge the value and re-add tz info

Not sure I understand this one. I though time.time() returned the seconds since Epoch?

Re:Dealing with Timezones in Python by nikcub on Friday July 15, 2011 @09:48AM (#2767334)
it does, but it assumes that the timestamp you are giving it is from your current timezone. compare:

    >>> time.mktime(datetime.datetime.now().utctimetuple())
    1310737652.0
    >>> int(datetime.datetime.utcnow().strftime('%s'))
    1310701659
my local timezone is +10, and mktime is adding it back in, hence why I always use strftime