Python datetime Object from String (A Complete Guide)

To convert a string to a date object in Python, use datetime.strptime() function.

Illustration of converting a string date to a date object with a robot like figure.

For example, let’s convert “Dec 1 2021 5:33 PM” into a date object:

from datetime import datetime

datetime_object = datetime.strptime("Dec 1 2021 5:33PM", "%b %d %Y %I:%M%p")

print(datetime_object)

Output:

2021-12-01 17:33:00

In this guide, you will learn how datetime.strptime() function works. You will also learn about the dateutil module.

How Does the datetime.strptime() Function Work

To convert a date string to a datetime object, you need to import the datetime module to your project.

In case you are wondering, the strptime() stands for string parse time.

The basic syntax of datetime.strptime() is:

datetime.strptime(date_string, format)

Where:

  • date_string is a date represented as a string.
  • format is the date parsing format.

In the example you saw earlier, the format was specified as “%b %d %Y %I:%M%p”. Let’s take a closer look at what each character means:

  • %b. Month name abbreviated.
  • %d. Day of the month as a zero-padded number.
  • %Y. Year number.
  • %I. Hour in a 12-hour clock as a zero-padded number.
  • %M. Minute is a zero-padded number.
  • %p. AM/PM based on the locale.

For instance:

from datetime import datetime

datetime_object = datetime.strptime("Dec 1 2021 5:33PM", "%b %d %Y %I:%M%p")

Read more about using the datetime module in Python.

Python datetime.strptime() Examples

Let’s have a look at some examples of using the datetime.strptime() function.

Example 1

Let’s convert a date in the format mm/dd/YY HH:MM:SS to a datetime object:

from datetime import datetime

datetime_str = "12/07/21 11:25:13"

datetime_object = datetime.strptime(datetime_str, "%m/%d/%y %H:%M:%S")

print(datetime_object)

# This is parsed as:
print(repr(datetime_object))

Output:

2021-12-07 11:25:13
datetime.datetime(2021, 12, 7, 11, 25, 13)

Example 2

You can call the date() method on a datetime object produced by the strptime() function to convert it to a date object.

For instance:

from datetime import datetime

date_str = '03-17-2021'

date_object = datetime.strptime(date_str, "%m-%d-%Y").date()

print(date_object)
print(repr(date_object))

Output:

datetime.date(2018, 9, 19)

Example 3

You can call the time() method on a datetime object produced by the strptime() function to convert it to a time object.

For instance:

from datetime import datetime

time_str = "12::43::19"
time_object = datetime.strptime(time_str, "%H::%M::%S").time()

print(time_object)
print(repr(time_object))

Output:

12:43:19
datetime.time(12, 43, 19)

Datetime Object from ISO Format in Python 3.7+

To convert date strings of format YYYY-MM-DD HH:MM:SS (ISO Format), call datetime.fromisoformat() function.

This assumes you are running Python 3.7+.

For example:

from datetime import datetime

date_string = "2021-12-01 10:44:53"
date_object = datetime.fromisoformat(date_string)

print(date_object)

Output:

2021-12-01 10:44:53

Alternative Approach

If you are dealing with lots of different time formats, you may benefit from using a third-party utility called dateutil.

This module guesses most of the date formats. This means you do not have to specify the format separately.

To use it, install the dateutil package by running the following in your command-line window:

pip install python-dateutil

Now you can use this package to parse dates from different date formats. Here are some examples of how it parses differently formatted date strings:

from dateutil import parser

d1 = parser.parse("Jul 22 2004 11:00AM")          # datetime.datetime(2004, 7, 22, 11, 0)
d2 = parser.parse("Sat Oct 11 17:13:46 UTC 2003") # datetime.datetime(2003, 10, 11, 17, 13, 46, tzinfo=tzutc())
d3 = parser.parse("February 18, 2020")            # datetime.datetime(2020, 2, 18, 0, 0)
d4 = parser.parse("01/03/2027 11:03")             # datetime.datetime(2027, 1, 3, 11, 3)
d5 = parser.parse("Aug 19, 2019 1:33PM")          # datetime.datetime(2019, 8, 19, 13, 33)

Dateutil Performance Issue

Notice that the dateutil module guesses the date formats on the fly. This involves some iteration behind the scenes, which makes the date parsing quite inefficient.

Let’s make a comparison by converting a date string 100,000 times with both datetime.strptime() and dateutil‘s parser.parse():

import time
from datetime import datetime
from dateutil import parser

start1 = time.time()
for _ in range(100_000):
    datetime.strptime("Dec 1 2021 5:33PM", "%b %d %Y %I:%M%p")
end1 = time.time()

strptime_parsing_time = end1 - start1
print(f"datetime.strptime(): {strptime_parsing_time}")

start2 = time.time()
for _ in range(100_000):
    parser.parse("Dec 1 2021 5:33PM")
end2 = time.time()

dateutil_parsing_time = end2 - start2
print(f"dateutil.parser: {dateutil_parsing_time}")

print(f"The dateutil is {dateutil_parsing_time / strptime_parsing_time} times slower than datetime.strptime().")

Output:

datetime.strptime(): 0.8942279815673828
dateutil.parser: 6.366821765899658
The dateutil is 7.119908901463847 times slower than datetime.strptime().

For this particular time format, the dateutil module’s parser was roughly 7 times slower than the datetime.strptime().

So even though using the dateutil module is appealing, you should use the built-in datetime.strptime() function.

Thanks for reading. Happy coding!

About the Author

Artturi Jalli
I'm an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.

Leave a Comment

Your email address will not be published. Required fields are marked *