Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse timezones with UTC offsets in Python?

Let's say I have a timezone like "2009-08-18 13:52:54-04". I can parse most of it using a line like this:

datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S")

However, I can't get the timezone to work. There's a %Z that handles textual timezones ("EST", "UTC", etc) but I don't see anything that can parse "-04".

like image 874
mike Avatar asked Aug 19 '09 19:08

mike


People also ask

How do you convert UTC time to other timezone in Python?

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.

How do you use UTC datetime in Python?

Getting the UTC timestampdatetime. now() to get the current date and time. Then use tzinfo class to convert our datetime to UTC. Lastly, use the timestamp() to convert the datetime object, in UTC, to get the UTC timestamp.

How do you time offset in Python?

The utcoffset() function is used to return a timedelta object that represents the difference between the local time and UTC time. This function is used in used in the datetime class of module datetime. Here range of the utcoffset is “timedelta(hours=24) <= offset <= timedelta(hours=24)”.

How do I get specific timezone in Python?

You can get the current time in a particular timezone by using the datetime module with another module called pytz . You can then check for all available timezones with the snippet below: from datetime import datetime import pytz zones = pytz. all_timezones print(zones) # Output: all timezones of the world.


2 Answers

Maybe you could use dateutil.parser.parse? That method is also mentioned on wiki.python.org/WorkingWithTime.

>>> from dateutil.parser import parse
>>> parse("2009-08-18 13:52:54-04")
datetime.datetime(2009, 8, 18, 13, 52, 54, tzinfo=tzoffset(None, -14400))

(is this question a duplicate?)

like image 88
conny Avatar answered Nov 10 '22 23:11

conny


use Babel, specifically parse_datetime.

like image 23
iElectric Avatar answered Nov 10 '22 23:11

iElectric