Question

I have some code as shown below, but the timezone %Z is returning: 01:04:48 GMT Daylight Time

I need it return: 01:04:48 GMT

import time

timenew = time.strftime('%H:%M:%S %Z')
print timenew

Anyone have any idea how I can fix/do this?

Was it helpful?

Solution

Lazy way:

time.strftime('%H:%M:%S %Z')[:13]

OTHER TIPS

The problem is that %Z isn't documented to give you any specific format at all; it just gives you:

Time zone name (no characters if no time zone exists).

With CPython 2.7 or 3.3 on POSIX platforms, it will usually give you something in the format EST/EDT for the major US timezones, but it may give you something in the format GMT/GMT Daylight Time (or British Summer Time or GMT Summer Time) for the major EU timezones, but that isn't guaranteed anywhere at all, and what you get elsewhere is hard to predict.

So, if you only care about your specific platform, and only about the major US and EU timezones, and you know that it's giving you GMT Daylight Time (rather than, say, British Summer Time, which you presumably don't want to truncate to Bri), you can do something like this:

tz = time.strftime('%Z')[:3]
if tz.endswith('DT'): tz = tz[0] + 'ST'
timenow = time.strftime(''%H:%M:%S ') + tz

If you look at the source, you can see that time.strftime ultimately just calls your platform's strftime. On POSIX platforms, the standard defines %Z as:

Replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists. [tm_isdst]

Although it isn't stated very clearly on that page, ultimately, what you get is the value of the extern variable tzname[0] or tzname[1] depending on isdst, and Python exposes tzset, so you can do something like this:

os.environ['TZ'] = 'GMT'
time.tzset()

And now, '%Z' is guaranteed to return GMT. Or you can leave Daylight/Summer Time support in, but just give both the same name:

os.environ['TZ'] = 'GMT+00GMT'

Or, ideally, you can feed in the right DST rules for the active timezone, just replacing the name.

You can force it to GMT using the gmtime:

In [11]: time.strftime('%H:%M:%S %z', time.gmtime())
Out[11]: '00:13:17 +0000'

However, it's now 00:13 GMT (rather than 1:13 DST).

GMT does not adjust for daylight savings time. You can hear it from the horse's mouth on this web site. "%Z" just means:

Time zone name (no characters if no time zone exists).

So you can just strip off the string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top