In this article, we will discuss how to convert different format string to a datetime or date or time object in Python.

Table of Contents

In Python, the datetime module provides a function strptime() to convert a string into a datetime object. Let’s have an overview of this function.

Syntax of datetime.strptime()

datetime.strptime(datetime_str, format):

Parameters

  • datetime_str: The string containing the date and time information.
  • format: The string explaining the format in which datetime_str includes the date and time info.
    • Based on the format provided, strptime() converts the datetime_str into a datetime object.

Returns:

  • If datetime_str contains the date and time information in the correct format, i.e., aligned with the format string, it returns the datetime object.

Important Note:

  • If there is a mismatch in the format specified and actual datetime string, it will result in ValueError.

Now let’s see some examples where we are going to use this strptime() function to convert string to a datetime object,

Convert string (‘DD/MM/YY HH:MM:SS ‘) to datetime object

Suppose we have date and time information in a string format ‘DD/MM/YY HH:MM:SS’ like ’25/12/20 11:12:13′. We can convert this string to a datetime object by passing the correct format in strptime i.e. ‘%d/%m/%y %H:%M:%S’. For example,

from datetime import datetime

datetime_str = '25/12/20 11:12:13'

# Convert String ( ‘DD/MM/YY HH:MM:SS ‘) to datetime object
datetime_obj = datetime.strptime(datetime_str, '%d/%m/%y %H:%M:%S')

print(datetime_obj)
print('Type of the object:')
print(type(datetime_obj))

Output:

2020-12-25 11:12:13
Type of the object:
<class 'datetime.datetime'>

We converted the string to a datetime object.

The format string we passed in strptime(), helped it to understand the information layout in the string object. The format string consists of format codes like,

  • %d – Represents the day of the month like 1,2,3….,30,31
  • %m – Represents the number of the month in year like 1,2,3….,11,12
  • %y – Represents the year in two digits like 19, 20 etc.
  • %H – Represents the hour like 01,02,…24
  • %M – Represents the minutes like 01,02,…60
  • %S – Represents the seconds like 01,02,…60

Then it checks how these format codes are organized in the string, like what characters they are separated by and what their positions are. Based on that, it parses the string and constructs a datetime object.

Let’s check out some other examples,

Convert string (‘MM/DD/YY HH:MM:SS ‘) to datetime object

In this example, we will change the order of format codes from the previous example,

from datetime import datetime

datetime_str = '12/25/2020 11:12:13'

# Convert String ( ‘MM/DD/YY HH:MM:SS ‘) to datetime object
datetime_obj = datetime.strptime(datetime_str, '%m/%d/%Y %H:%M:%S')

print(datetime_obj)
print('Type of the object:')
print(type(datetime_obj))

Output

2020-12-25 11:12:13
Type of the object:
<class 'datetime.datetime'>

We converted the string to a datetime object.

Convert string to datetime and handle ValueError

If the datetime string and the format string passed in strptime() function are not compatible, then it can cause a ValueError. For example,

from datetime import datetime

datetime_str = '25/12/2020 11:12:13'
datetime_obj = datetime.strptime(datetime_str, '%d-%m-%Y %H:%M:%S')

Output:

ValueError: time data '25/12/2020 11:12:13' does not match format '%d-%m-%Y %H:%M:%S'

Here we the string contains the date and time information in format’ MM/DD/YY HH:MM:SS’, but we passed the format string as ‘%d-%m-%Y %H:%M:%S’. Both the datetime string and format are not compatible, so it raised a ValueError.

To handle this kind of scenario, either pass the correct format or use the try/except. For example,

from datetime import datetime

datetime_str = '25/12/2020 11:12:13'
try:
    datetime_obj = datetime.strptime(datetime_str, '%d-%m-%Y %H:%M:%S')
    print(type(datetime_obj))
    print(datetime_obj)
except ValueError as e:
    print(e)

Output:

time data '25/12/2020 11:12:13' does not match format '%d-%m-%Y %H:%M:%S'

Python: Convert string to datetime – ( string format yyyy-mm-dd hh-mm-ss)

The format code %Y represents the year in 4 digits like 2019, 2020, etc. We are going to use that in the format string,

from datetime import datetime

# python string to datetime yyyy-mm-dd hh-mm-ss
datetime_str = '2020-12-24 11-12-13'
datetime_obj = datetime.strptime(datetime_str, '%Y-%m-%d %H-%M-%S')

print(type(datetime_obj))
print(datetime_obj)

Output:

<class 'datetime.datetime'>
2020-12-24 11:12:13

We converted the string to a datetime object.

Python: Convert string to datetime – ( string format MMM DD YYYY HH:MM:SS)

The format code %b represents the month in 3 characters like Jan, Feb, etc. We are going to use that in the format string,

from datetime import datetime

datetime_str = 'Dec 12 2020 11:12:13'
datetime_obj = datetime.strptime(datetime_str, '%b %d %Y %H:%M:%S')

print(type(datetime_obj))
print(datetime_obj)

Output:

<class 'datetime.datetime'>
2020-12-24 11:12:13

We converted the string to a datetime object.

Python: Convert string to datetime with milliseconds- ( string format DD/MM/YY HH:MM:SS:FFFFFF)

The format code %f represents the milliseconds in 6 digits. We are going to use that in the format string,

from datetime import datetime

datetime_str = '25/12/20 11:12:13.453'

datetime_obj = datetime.strptime(datetime_str, '%d/%m/%y %H:%M:%S.%f')

print(type(datetime_obj))
print(datetime_obj)

Output:

<class 'datetime.datetime'>
2020-12-25 11:12:13.453000

We converted the string to a datetime object with millisecond information.

Python: Convert string to datetime with timezone

The format code %z represents the timezone information like +05:30 or -02:00 etc. We are going to use that in the format string,

from datetime import datetime

datetime_str = '25/12/20 11:12:13+05:30'
datetime_obj = datetime.strptime(datetime_str, '%d/%m/%y %H:%M:%S%z')

print(type(datetime_obj))
print(datetime_obj)
print(datetime_obj.tzinfo)

Output:

<class 'datetime.datetime'>
2020-12-25 11:12:13+05:30
UTC+05:30

We converted the string to a datetime object with timezone information.

Python: Convert string to date object

Using strptime(), we can convert a datetime string to the datetime object. Then by calling the date() function on the datetime object, we can have a date object. For example,

from datetime import datetime

datetime_str = '2020-12-25'
datetime_obj = datetime.strptime(datetime_str, '%Y-%m-%d').date()

print(type(datetime_obj))
print(datetime_obj)

Output:

<class 'datetime.date'>
2020-12-25

Python: Convert string to time object

Using strptime(), we can convert a datetime string to the datetime object. Then by calling the time() function on the datetime object, we can have a time object. For example,

from datetime import datetime

datetime_str = '11::12::34'
datetime_obj = datetime.strptime(datetime_str, '%H::%M::%S').time()

print(type(datetime_obj))
print(datetime_obj)

Output:

<class 'datetime.time'>
11:12:34

Summary

Using the strptime() function of the datetime module in Python, we can convert a string to a datetime or date or time object. Using the format codes, we can handle the different string formats of date and time information.

Join a list of 2000+ Programmers for latest Tips & Tutorials