问题
I am in the US and I want to get the UTC time (without the effect of Daylight Saving Time) for a piece of code:
localtime = strftime("%m%d%y%H%M", gmtime())
Right now that code give me time in Greenwich, England. I know that I have a time offset of -8 (GMT -8). How can I get the UTC time to a specific timezone? (using Python library, not casting the hour to integer, - 8, and than convert it back)
Thank you.
回答1:
Try the datetime module:
datetime.datetime.utcnow() + datetime.timedelta(hours=-8)
BTW, UTC doesn't have timezones, it's Universal Co-ordinated Time, it's the same everywhere.
回答2:
Just use the localtime() rather than gmtime() function:
localtime = time.strftime("%m%d%y%H%M", time.localtime())
From the python time module: "Like gmtime() but converts to local time. If secs is not provided or None, the current time as returned by time() is used. The dst flag is set to 1 when DST applies to the given time."
To see if DST applies:
time.daylight
回答3:
Supporting timezones at whatever level of detail is required is up to the application. The rules for time adjustment across the world are more political than rational, and there is no standard suitable for every application.
There is a useful third party module for that purpose: http://pytz.sourceforge.net/
来源:https://stackoverflow.com/questions/6528391/python-how-to-get-utc-time-given-timezone