Python: How to get UTC time given TIMEZONE

◇◆丶佛笑我妖孽 提交于 2019-12-11 02:18:19

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!