'NameError: name 'UTC' is not defined
The output of datetime.datetime.now()
outputs in my native timezone of UTC-8. I'd like to convert that to an appropriate timestamp with a tzinfo of UTC.
from datetime import datetime, tzinfo
x = datetime.now()
x = x.replace(tzinfo=UTC)
^ outputs NameError: name 'UTC' is not defined
x.replace(tzinfo=<UTC>)
outputs SyntaxError: invalid syntax
x.replace(tzinfo='UTC')
outputs TypeError: tzinfo argument must be None or of a tzinfo subclass, not type 'str'
What is the correct syntax to use to accomplish my example?
Solution 1:[1]
You'll need to use an additional library such as pytz
. Python's datetime
module doesn't include any tzinfo
classes, including UTC, and certainly not your local timezone.
Edit: as of Python 3.2 the datetime
module includes a timezone
object with a utc
member. The canonical way of getting the current UTC time is now:
from datetime import datetime, timezone
x = datetime.now(timezone.utc)
You'll still need another library such as pytz
for other timezones. Edit: Python 3.9 now includes the zoneinfo
module so there's no need to install additional packages.
Solution 2:[2]
If all you're looking for is the time now in UTC, datetime has a builtin for that:
x = datetime.utcnow()
Unfortunately it doesn't include any tzinfo, but it does give you the UTC time.
Alternatively if you do need the tzinfo you can do this:
from datetime import datetime
import pytz
x = datetime.now(tz=pytz.timezone('UTC'))
You may also be interested in a list of the timezones: Python - Pytz - List of Timezones?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Community |