Aminoff
Aminoff

Reputation: 717

How to use tzutc()

What am I missing, how do I get this function to work?

import dateutil.parser
import datetime

my_date = datetime.datetime(2000, 1, 1, 0, 0, 0, 000000, tzinfo=tzutc())

print(my_date)

Gives me the error:

NameError: name 'tzutc' is not defined

Upvotes: 42

Views: 41483

Answers (2)

cottontail
cottontail

Reputation: 23081

Instead of the third-party library object tzutc, timezone info such as UTC can be passed using the standard library.

Python>=3.11

You can use datetime.UTC for UTC specifically.

from datetime import datetime, UTC

my_date = datetime(2000, 1, 1, 0, 0, 0, tzinfo=UTC)

You can verify that datetime(2000, 1, 1, 0, 0, 0, tzinfo=tzutc()) == my_date is indeed True.

Python>=3.9

You can also use zoneinfo.ZoneInfo. Simply pass timezone as a string (e.g. "UTC") to initialize an IANA time zone. You can set all sorts of other timezones using its name (it uses tzdata to look up names); you can see all possible names via zoneinfo.available_timezones().

from datetime import datetime
from zoneinfo import ZoneInfo

my_date_1 = datetime(2000, 1, 1, 0, 0, 0, tzinfo=ZoneInfo("UTC"))

Again, you can verify that datetime(2000, 1, 1, 0, 0, 0, tzinfo=tzutc()) == my_date_1 is True.

Python>=3.2

In older versions of Python, you can set UTC via datetime.timezone:

from datetime import datetime, timezone, timedelta
my_date_2 = datetime(2000, 1, 1, 0, 0, 0, tzinfo=timezone.utc)
my_date_3 = datetime(2000, 1, 1, 0, 0, 0, tzinfo=timezone(timedelta(0)))

Upvotes: 1

jojomojo
jojomojo

Reputation: 1342

You did not import it:

from dateutil.tz import tzutc

Upvotes: 89

Related Questions