NameError: name 'UTC' not defined

The output of datetime.datetime.now() is output in my UTC-8 timezone. I would like to convert this to an appropriate timestamp with tzinfo UTC.

 from datetime import datetime, tzinfo x = datetime.now() x = x.replace(tzinfo=UTC) 

^ output NameError: name 'UTC' not defined

x.replace(tzinfo=<UTC>) displays syntax x.replace(tzinfo=<UTC>) : invalid syntax

x.replace(tzinfo='UTC') output TypeError: the tzinfo argument must be None or a subclass of tzinfo, not type 'str'

What is the correct syntax to execute my example?

+7
source share
2 answers

You will need to use an additional library such as pytz . The Python datetime does not include tzinfo classes in tzinfo , including UTC, and, of course, not your local time zone.

Change: utc with Python 3.2 the datetime module includes a timezone object with a utc member. Canonical way to find out the current time UTC:

 from datetime import datetime, timezone x = datetime.now(timezone.utc) 

You will still need another library, such as pytz for other time zones.

+9
source

If all you are looking for is UTC time, datetime has a built-in for this:

 x = datetime.utcnow() 

Unfortunately, it does not contain any tzinfo, but it gives you UTC time.

Alternatively, if you need tzinfo, you can do this:

 from datetime import datetime import pytz x = datetime.now(tz=pytz.timezone('UTC')) 

You may also be interested in the list of time zones: Python - Pytz - List of time zones?

+3
source

Source: https://habr.com/ru/post/919808/


All Articles