Python Parse String to datetime

Aug 7, 2019

Solution 1: ISO Format (Python 3.7)

import datetimedate_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 datetimedate_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_parserdate_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'# ordate_str = '2019-08-07T15:36:11.618Z'# ordate_str = '2019-08-07T15:36:11Z'

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

import datetimedate_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_parserdate_str = '2019-08-07T15:36:11.618911Z'dateutil_parser.parse(date_str)

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.