如何在Python中获取UTC日期字符串? [英] How to get an UTC date string in Python?

查看:131
本文介绍了如何在Python中获取UTC日期字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将utc日期字符串作为 YYYYMMDD

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')

我曾经做过:

datetime.date.today().strftime()

但这给了我本地TZ的日期字符串

but this gives me date string in local TZ

如何获取UTC日期字符串?

How can I get an UTC date string?

推荐答案

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

或者正如Davidism指出的那样,这也可以工作:

Or as Davidism pointed out, this would also work:

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

我更喜欢第一种方法,因为它会让您养成使用时区感知日期时间的习惯-但正如JF Sebastian指出的那样-它需要Python 3.2+。第二种方法将同时在2.7和3.2分支中起作用。

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.

这篇关于如何在Python中获取UTC日期字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆