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?
You can use the datetime module to convert a datetime to a UTC timestamp in Python. If you already have the datetime object in UTC, you can the timestamp() to get a UTC timestamp. This function returns the time since epoch for that datetime object.
The zoneinfo module provides a concrete time zone implementation to support the IANA time zone database as originally specified in PEP 615.
The pytz package encourages using UTC for internal timezone representation by including a special UTC implementation based on the standard Python reference implementation in the Python documentation. The UTC timezone unpickles to be the same instance, and pickles to a smaller size than other pytz tzinfo instances.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With