World's Best AI Learning Platform with profoundly Demanding Certification Programs
Designed by IITians, only for AI Learners.
Designed by IITians, only for AI Learners.
New to InsideAIML? Create an account
Employer? Create an account
Python 3 .2+ has support for %z format when parsing a string into a datetime object.
import datetime dt = datetime.datetime.strptime("2021-04-15T08:27:18-0500", "%Y-%m-%dT%H:%M:%S%z")
>dt datetime.datetime(2021, 4, 15, 8, 27, 18, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=68400)))
For other versions of Python, you can use an external library such as dateutil , which makes parsing a string with
timezone into a datetime object is quick.
import dateutil.parser dt = dateutil.parser.parse("2021-04-15T08:27:18-0500")
The dt variable is now a datetime object with the following value:
datetime.datetime(2021, 4, 15, 8, 27, 18, tzinfo=tzoffset(None, -18000))
from datetime import datetime datetime_string = 'Oct 1 2016, 00:00:00' datetime_string_format = '%b %d %Y, %H:%M:%S' datetime.strptime(datetime_string, datetime_string_format) # datetime.datetime(2016, 10, 1, 0, 0)