Reputation: 717
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
Reputation: 23081
Instead of the third-party library object tzutc
, timezone info such as UTC can be passed using the standard library.
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.
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.
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