time.strftime Timezone issue

Tim Peters tim.one at comcast.net
Sun Jun 13 07:55:25 CEST 2004


[Allen Unueco]
> As it turns out it was my mistake for using gmtime() not localtime(). Not
> really any point is formating the timezone when you are asking for the
> time in UTC. But it is a little strange why it should change, if anything
> I would assume it would change to UTC.

These are wrappers around standard C functions.  C's struct tm doesn't have
a time zone member, so strftime has no idea which time zone the struct tm
passed to it may be intended to represent.  IOW, strftime's idea of time
zone doesn't come from its argument, and can not come from its argument.
Its idea of whether daylight time is in effect comes from its argument's
tm_isdst flag, and gmtime() always sets that to zero; gmtime() must set
tm_isdst to something, and since daylight time is never in effect in UTC, 0
is the only reasonable value for gmtime() to give to tm_isdst.

If you want strftime() to believe the appropriate time zone is UTC, you need
to call tzset() (or some platform-dependent moral equivalent) to talk C into
believing the time zone is UTC.

C's time facilities are a bloody mess.

> Here is the output from my Debian (woody) box
>
> Python 2.2.1 (#1, Feb 28 2004, 00:52:10)
> [GCC 2.95.4 20011002 (Debian prerelease)] on linux2 
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import time
> >>> time.daylight
> 1
> >>> time.strftime("%Z")
> 'EDT'
> >>> time.strftime("%Z", time.localtime())
> 'EDT'
> >>> time.strftime("%Z", time.gmtime())
> 'EST'

All as it must be <wink>.

> It seems to work fine on my OSX system, although I'm confused by
> time.daylight being set to '1' when it's NZST right now, down here.

I should have noted this the first time:  as the docs say, time.daylight
doesn't say whether daylight time is in effect, it has only to do with
whether the current time zone *has* a notion of "daylight time".  If you
want to know whether daylight time is currently in effect,

    time.localtime().tm_isdst

is the way to spell it.

> Python 2.3 (#1, Sep 13 2003, 00:49:11)
> [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import time
> >>> time.daylight
> 1
> >>> time.strftime("%Z")
> 'NZST'
> >>> time.strftime("%Z", time.gmtime())
> 'NZST'
> >>> time.strftime("%Z", time.localtime())
> 'NZST'

Again all as it should be.  If you don't want the 'NZST' result for
gmtime(), you'll need to use tzset() first to change C's notion of the time
zone in effect.  Exactly how to do this (or even whether time.tzset()
exists) depends on your platform C library; tzset() isn't a standard C
function; POSIX defines tzset(), but doesn't define a set of time zone names
to use with it.






More information about the Python-list mailing list