Working in web application sometimes we have the situation where we need to receive a time string and convert it to datetime and save to our database. In this post I will demonstrate how to achieve it in Python. It is quite simple.
The string is passed in with ISO8601 format. That is, it is something like this:
isodate = "2020-09-25T00:00:00.000 PST"
Python has a dateutil.parser which supports converting a ISO8601 string to a datatime object. It is in fact very easy to use.
import dateutil.parser
time = dateutil.parser.parse(isodate)
As simple as that. However we have a small problem, the time here is interpreted using local time zone. From our input it is clear the string is from PST time zone. To set the time zone, we need to use tzinfo.
from dateutil import tz
tzinfos = {"PST": tz.gettz('America/Los_Angeles')}
time = dateutil.parser.parse(isodate, tzinfos=tzinfos)
This way the time object will be interpreted in PST time zone. tzinfos is a dictionary, which means we can also provide more different time zones. Any time zone abbrevation added will then be available in the interpretation.
Now, if you want to convert the time to a local time zone, the easier way to do this is by using pytz.
import pytz
localtz = 'America/New_York'
localtime = time.astimezone(pytz.timezone(localtz))
References:
https://dateutil.readthedocs.io/en/stable/tz.html
https://dateutil.readthedocs.io/en/stable/parser.html