如何在 Python 中获取 UTC 日期字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17822158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get an UTC date string in Python?
提问by GJain
I am trying to get utc date string as "YYYYMMDD"
我正在尝试将 UTC 日期字符串设为“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
但这给了我本地 TZ 中的日期字符串
How can I get an UTC date string?
如何获取 UTC 日期字符串?
采纳答案by Matt Johnson-Pint
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.
我更喜欢第一种方法,因为它让您养成使用时区感知日期时间的习惯——但正如 JF Sebastian 指出的那样——它需要 Python 3.2+。第二种方法适用于 2.7 和 3.2 分支。