How to get an UTC date string in Python? [duplicate]

為{幸葍}努か 提交于 2019-12-31 17:51:14

问题


I am trying to get utc date string as "YYYYMMDD"

For now I do the following,

nowTime =  time.gmtime();
nowDate = date(nowTime.tm_year, nowTime.tm_mon, nowTime.tm_mday)
print nowDate.strftime('%Y%m%d')

I used to do:

datetime.date.today().strftime()

but this gives me date string in local TZ

How can I get an UTC date string?


回答1:


from datetime import datetime, timezone
datetime.now(timezone.utc).strftime("%Y%m%d")

Or as Davidism pointed out, this would also work:

from datetime import datetime
datetime.utcnow().strftime("%Y%m%d")

I prefer the first approach, as it gets you in the habit of using timezone aware datetimes - but as J.F. Sebastian pointed out - it requires Python 3.2+. The second approach will work in both 2.7 and 3.2 branches.



来源:https://stackoverflow.com/questions/17822158/how-to-get-an-utc-date-string-in-python

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