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.
Converting localized string date representation to UTC in python
652 views Asked by srjt At
2
There are 2 answers
0
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>)
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 withpytz.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:
And we get: