时区:有没有办法在 Python 中打印带有日期时间的 GMT(格林威治标准时间)?

Timezone: Is there a way to print GMT (Greenwich Mean Time) with datetime in Python?

代码到目前为止工作正常。我只是收录它以供参考。

import datetime

#prints current local datetime with a time zone of none
dt_today = datetime.datetime.today()
# gives option to introduce a timezone
dt_now = datetime.datetime.now()
# utcnow does not signify a timezone-aware datetime
# instead it offers utc info set to now but tcinfo still set to none
dt_utcnow = datetime.datetime.utcnow()

print(dt_today)

print(dt_now)

print(dt_utcnow)

print(dt_utcnow.strftime('%Y-%m-%d %H:%M:%S.%f %Z'))

我尝试了显而易见的方法:

dt_gmt = datetime.datetime.gmt()

但这没有用。

而不是 datetime.utcnow(),尝试 datetime.now(timezone.utc),如 this answer.

示例如下:

import datetime

#prints current local datetime with a time zone of none
dt_today = datetime.datetime.today()
# gives option to introduce a timezone
dt_now = datetime.datetime.now()
# utcnow does not signify a timezone-aware datetime
# instead it offers utc info set to now but tcinfo still set to none
dt_utcnow = datetime.datetime.now(datetime.timezone.utc)

print(dt_now)

print(dt_utcnow)
print(dt_utcnow.strftime('%Y-%m-%d %H:%M:%S.%f %Z'))

输出:

2021-10-28 19:13:35.069610
2021-10-28 23:13:35.069610+00:00
2021-10-28 23:13:35.069610 UTC

替代方法,如果您真的想包含“GMT”:

print(dt_utcnow.isoformat().replace("+00:00", " GMT"))

打印:2021-10-28T23:18:35.637448 GMT

help(datetime) 导致了 python 库的日期时间部分,它阐明了 gmtimestrftime 原来是我要找的东西:

import time

print("\nGMT: "+time.strftime("%a, %d %b %Y %I:%M:%S %p %Z", time.gmtime())) 
print("Local: "+strftime("%a, %d %b %Y %I:%M:%S %p %Z\n"))