且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Python中获取UTC日期字符串?

更新时间:2023-11-14 22:52:04

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.