Is there a built-in library or does anyone have available a function to convert a string timezone such as "America/New_York" to a datetime.tzinfo object?
Thanks.
We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.
Converting Between TimezonesUse the datetime. astimezone() method to convert the datetime from one timezone to another. This method uses an instance of the datetime object and returns a new datetime of a given timezone.
tzinfo is an abstract base class. It cannot be instantiated directly. A concrete subclass has to derive it and implement the methods provided by this abstract class. The instance of the tzinfo class can be passed to the constructors of the datetime and time objects.
tzinfo.utcoffset(self, dt) : return offset of local time from UTC, in minutes east of UTC. tzinfo.dst(self, dt) : return the daylight saving time (DST) adjustment, in minutes east of UTC, or None if DST information isn't known.
Yes, you need the pytz
library:
import datetime, pytz
zoneName = 'America/New_York'
now = datetime.datetime.now(pytz.timezone(zoneName))
returns:
datetime.datetime(2011, 3, 16, 1, 39, 33, 87375, tzinfo=<DstTzInfo 'America/New_York' EDT-1 day, 20:00:00 DST>)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With