Skip to content
Advertisement

Datetime Timezones from String

I am trying to figure out how to make a datetime object aware through using a variable. I grab the timezone of the user and pass it through a form to be used.

I have tried both of the below methods and am not having much success

JavaScript

This will then give me errors of TypeError: tzinfo argument must be None or of a tzinfo subclass, not type 'str'

The timezone will not always be known upfront, so it would not be possible to simply have the argument be as such tzinfo=timezone.utc.

Advertisement

Answer

Using dateutil or Python 3.9’s zoneinfo:

JavaScript

Note: you can directly create a datetime object. If you use pytz (deprecated with Python 3.9), you must use the localize method of the timezone object. Otherwise, you’ll end up with LMT (local mean time):

JavaScript

Side-note: interestingly, dateutil returns the deprecated GB-Eire time zone name for Europe/London. It is correct nevertheless, no worries.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement