[Tutor] problem with time module
Dick Moores
rdm at rcblue.com
Sun Aug 15 07:39:43 CEST 2004
Tim Peters wrote at 21:51 8/14/2004:
>[Dick Moores]
> > From the time module doc at
> > <http://docs.python.org/lib/module-time.html>,
> > I expected mktime(localtime()) and time() to be approx. 7*3600 seconds
> > apart (I'm on the U.S. west coast, in -0700).
>
>I don't know how you're reading the docs. There are two ways of
>representing time in that module:
>
>1. Timestamps, which are floats. These are always seconds from the epoch,
> as measured in UTC. No exceptions.
>
>2. struct_time thingies. These are broken out into year, month, etc. They
> don't contain time zone info explicitly, but correct interpretation
> requires
> anyway that you know which time zone was intended. mktime() assumes
> its input is expressed in local time; there's nothing in the time
> module that
> converts a UTC struct_time to a timestamp, although calendar.timegm()
> does that.
>
>localtime() creates a #2. mktime(localtime()) produces a #1, so must
>be UTC. time() produces a #1, so must also be UTC. Therefore I
>expect the same result from both, although mktime()'s input doesn't
>have a fraction-of-a-second member so I expect an exact integer (in
>floating format) form mktime().
>
> > But they're not:
>
>Good <wink>!
>
> > >>> from time import *
> > >>> mktime(localtime());time()
> > 1092510279.0
> > 1092510279.2650001
> >
> > Have I misunderstood something?
>
>Yes, but since you didn't lay out your reasoning, I can't guess which
>step got off track.
OK, here's my reasoning. From the doc,
"mktime( t)
This is the inverse function of localtime(). Its argument is the
struct_time or full 9-tuple (since the dst flag is needed; use -1 as the
dst flag if it is unknown) which expresses the time in local time, not
UTC. It returns a floating point number, for compatibility with time().
If the input value cannot be represented as a valid time, either
OverflowError or ValueError will be raised (which depends on whether the
invalid value is caught by Python or the underlying C libraries). The
earliest date for which it can generate a time is platform-dependent."
If mktime(t) is the inverse of localtime(), I thought this implied that
the floating point number mktime(localtime()) returned would be seconds
from the epoch based on my local time. I saw nothing that said that all
timestamps are based on UTC (although I can see now that it's a Good
Thing they are). I did understand that time() is based on UTC. Therefore
I concluded that mktime(localtime()) should be about 7 hours less than
time().
Thanks very much for your lucid clarification.
Dick Moores
More information about the Tutor
mailing list