Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string timezones in form (Country/city) into datetime.tzinfo

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.

like image 766
Adam M-W Avatar asked Mar 16 '11 05:03

Adam M-W


People also ask

How do I convert a string to a datetime in Python?

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.

How do I change the timezone in datetime?

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.

What is Tzinfo datetime?

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.

What is Tzinfo =< UTC?

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.


1 Answers

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>)
like image 71
eumiro Avatar answered Sep 23 '22 13:09

eumiro