Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 260
Randall Ma Avatar asked Jul 05 '12 22:07

Randall Ma


People also ask

Is Python datetime in UTC?

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.

Which Python library is used for time zone?

The zoneinfo module provides a concrete time zone implementation to support the IANA time zone database as originally specified in PEP 615.

What is PYTZ UTC?

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.


2 Answers

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.

like image 143
Mark Ransom Avatar answered Sep 21 '22 21:09

Mark Ransom


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?

like image 45
fantabolous Avatar answered Sep 19 '22 21:09

fantabolous