19
votes
import time
print time.strftime("%a, %d %b %Y %I:%M %p %Z", time.gmtime())

I live in California. For some reason, this code is reporting the time in GMT, instead of respecting the system time zone. I know that strftime knows I'm in pacific, because it still prints 'PST' at the end, but it's still 8 hours ahead. Is anyone else noticing this? Anyone know what's either wrong with my system or my code?

EDIT: running date at the command line gives me the correct date. Additionally, I've run this on two different computers (mac and linux) and they both report 8 hours ahead. Are you expected to correct for timezone before using strftime?

2
What if you just run "date" on the command line? Could it be that your computer's time is set to GMT, but has a California timezone?Ken Kinder

2 Answers

33
votes

time.gmtime() returns the time in UTC. What you need is time.localtime(), which is timezone-aware. This behaviour is well-documented in the time module documentation.

EDIT:

To convert any time.time() style timestamp to a struct_time, you can supply an argument to time.localtime():

>>> print time.strftime("%a, %d %b %Y %I:%M:%S %p %Z", time.localtime(10.5))
Thu, 01 Jan 1970 02:00:10 AM EET
1
votes

To change the timezone on your unix system, do something like this:

ln -sf /usr/share/zoneinfo/America/Los_Angeles /etc/localtime

Browse around in /usr/share/zoneinfo/ to find what you want and alter the command above