Python Parse String to datetime

March 27, 2020

Solution 1: ISO Format (Python 3.7)

import datetime

date_str = '2019-07-11'
d = datetime.datetime.fromisoformat(date_str)
date_str = '2019-07-11T21:09:55'
d = datetime.datetime.fromisoformat(date_str)
date_str = '2019-07-11 21:09'
d = datetime.datetime.fromisoformat(date_str)

Solution 2: strptime format

import datetime

date_str = '2019-07-11'
d = datetime.datetime.strptime(date_str, '%Y-%m-%d')
date_str = '2019-07-11T21:09:55'
d = datetime.datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%S')
date_str = '2019-07-11T21:09:55.003Z'
d = datetime.datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S.%fZ")

NOTE: Refer strptime format directives.

Solution 3: python-dateutil (flexible format)

pip install python-dateutil
from dateutil import parser as dateutil_parser

date_str = '2019-07-11'
d = dateutil_parser.parse(date_str)
date_str = '2019-07-11T21:09:55'
d = dateutil_parser.parse(date_str)
date_str = 'Sat Jul 11 21:09:55 2019'
d = dateutil_parser.parse(date_str)

NOTE: Refer dateutil

ISO-8601 date format

date_str = '2019-08-07T15:36:11.618911Z'
# or
date_str = '2019-08-07T15:36:11.618Z'
# or
date_str = '2019-08-07T15:36:11Z'

If you know the miliseconds decimals and whether it contains timezone or not

import datetime

date_str = '2019-08-07T15:36:11Z'
datetime.datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S%z")

NOTE: datetime.fromisoformat doesn’t work if date_str with Z: This does not support parsing arbitrary ISO 8601 strings - it is only intended as the inverse operation of datetime.isoformat().

For more format flexibility and reliability

from dateutil import parser as dateutil_parser

date_str = '2019-08-07T15:36:11.618911Z'
dateutil_parser.parse(date_str)
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.