Converting localized string date representation to UTC in python

613 views Asked by At

How do I convert the following localized datetime string to UTC datetime. The string has date, time and timezone mentioned in it e.g. May 15,2015, 04.24AM IST, here IST is Indian Standard Time. It can be any time zone. I tried using pytz but couldn't make it work.

2

There are 2 answers

0
Andrzej Pronobis On

The thing is that it's quite difficult to parse a string with an abbreviated timezone information. But, if you know your timezone, then you can look up it's name recognized by pytz. You can even list all timezone names with pytz.all_timezones.

In your case it is 'Asia/Calcutta' and this should work to convert it to UTC. Just strip the timezone information from the string and add it later:

import pytz
import datetime

# String without timezone info
str = "May 15, 2015, 04.24AM"
# Parse it to naive time
dt = datetime.datetime.strptime(str, "%b %d, %Y, %I.%M%p")
# Localize it as Asia/Calcutta
dt_localized = pytz.timezone('Asia/Calcutta').localize(dt)
# Convert it to UTC
dt_utc = dt_localized.astimezone(pytz.timezone('UTC'))

And we get:

>>> dt
datetime.datetime(2015, 5, 15, 4, 24)

>>> dt_localized
datetime.datetime(2015, 5, 15, 4, 24, tzinfo=<DstTzInfo 'Asia/Calcutta' IST+5:30:00 STD>)

>>> dt_utc
datetime.datetime(2015, 5, 14, 22, 54, tzinfo=<UTC>)
0
Alexander On

First, let's strip your date string of the IST timezone and then assign it the Asia/Calcutta timezone.

import pytz

dt_str = "May 15, 2015, 04.24AM IST"
dt_str_naive = dt_str[:-4]

new_dt = (pytz.timezone('Asia/Calcutta')
          .localize(dt.datetime.strptime(dt_str_naive, "%b %d, %Y, %I.%M%p"))) 

Now that it is timezone aware, you can assign it to the UTC timezone:

>>> new_dt.astimezone(pytz.UTC)
datetime.datetime(2015, 5, 14, 22, 54, tzinfo=<UTC>)