UTC equivalent of time.mktime() ?

Graham Ashton gashton at cmedltd.com
Wed Apr 17 10:40:51 EDT 2002


Sorry to perpetuate the time theme, but I'm hoping somebody will cast an
eye over the following for me.

I'm trying to work out how to convert dates specified as strings (e.g.
"1 Jan 1970") into seconds since the epoch in UTC (e.g. 0). In a fit of
stupidity I've got stuck on a UTC vs localtime issue. If I explain what
I've been doing you'll see what I mean.

My approach is as follows:

  - use time.strptime() to convert the string into a time tuple

  - use time.mktime() to convert the tuple into seconds since the epoch
    (which is in localtime, for some God awful reason that continues to
     elude me - why?)

  - modify the epoch value according to the local time zone and DST
    (which seems horridly hackish).

In code, it looks like this:

Python 2.2 (#2, Mar 11 2002, 13:24:00) 
[GCC 2.95.3 20010315 (release)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> s = "1 Jan 1970"
>>> tup = time.strptime(s, "%d %b %Y")
>>> tup
(1970, 1, 1, 0, 0, 0, 3, 1, 0)
>>> secs = time.mktime(tup)
>>> secs  # (I'm in the UK)
-3600.0
>>> def local2utc(secs):
...     if time.daylight:
...         return secs - time.timezone - time.altzone
...     else:
...         return secs - time.timezone
... 
>>> local2utc(secs)
0.0

I'm not convinced that a sensible implementation of time keeping
libraries would force me to go to the effort of writing local2utc() in
order to convert "1 Jan 1970" to 0, so suspect that I've missed
something rather large. ;)

Thanks.

P.S. I've tried getting strptime() to understand %Z in it's format
string, and specify the timezone in the initial date string, but it
can't do it (even though the docs state that it understands everything
that stftime() does). Is this a bug, or a platform dependent thing? (I
suspect the latter -- I'm on Linux).

-- 
Graham Ashton






More information about the Python-list mailing list