NameError:名称“UTC”未定义
NameError:名称“UTC”未定义
datetime.datetime.now()
的输出是在我的本地时区 UTC-8。我想将其转换为具有 UTC tzinfo 的适当时间戳。
from datetime import datetime, tzinfo x = datetime.now() x = x.replace(tzinfo=UTC)
^ 输出 NameError: name \'UTC\' is not defined
x.replace(tzinfo=)
输出 SyntaxError: invalid syntax
x.replace(tzinfo=\'UTC\')
输出 TypeError: tzinfo argument must be None or of a tzinfo subclass, not type \'str\'
使用正确的语法来实现我的示例是什么?
admin 更改状态以发布 2023年5月21日
如果你所需要的只是UTC时间,datetime 已内置了相关功能:
x = datetime.utcnow()
不过,它不含任何时区信息,但可以提供UTC时间。
另外,如果你确实需要时区信息,可以这样实现:
from datetime import datetime import pytz x = datetime.now(tz=pytz.timezone('UTC'))
你可能还会对时区列表感兴趣: Python - Pytz - List of Timezones?
你需要使用额外的库,如pytz
。 Python的datetime
模块不包括任何tzinfo
类,包括UTC,当然也不包括你的本地时区。
编辑:自Python 3.2以来,datetime
模块包括具有utc
成员的timezone
对象。现在获取当前UTC时间的规范方式是:
from datetime import datetime, timezone x = datetime.now(timezone.utc)
对于其他时区,您仍然需要使用类似pytz
的其他库。编辑: Python 3.9现在包含了zoneinfo
模块,因此无需安装其他软件包。