Introduction
Python's datetime and time modules both include a strptime() class method for converting strings to objects.
In this article, you will use strptime() to convert strings to datetime objects and struct_time().
Convert string to datetime object using datetime.strptime()
The syntax of the datetime.strptime() method is as follows:
datetime.strptime(date_string, format)
The datetime.strptime() method returns a datetime object that corresponds to the date_string parsed by the format. Both arguments are required and must be strings.
For more details on the format commands used in datetime.strptime(), see the strftime() and strptime() formatting codes in the Python documentation.
Convert string to datetime.datetime() object example
The following example converts a datetime string to a datetime.datetime() object and prints the class name and value of the resulting object:
from datetime import datetime
datetime_str = '09/19/22 13:55:26'
datetime_object = datetime.strptime(datetime_str, '%m/%d/%y %H:%M:%S')
print(type(datetime_object))
print(datetime_object) # printed in default formatThe output is:
<class 'datetime.datetime'>
2022-09-19 13:55:26Convert string to datetime.date() object example
The following example converts a date string to a datetime.date() object and prints the class type and value of the resulting object:
from datetime import datetime
date_str = '09-19-2022'
date_object = datetime.strptime(date_str, '%m-%d-%Y').date()
print(type(date_object))
print(date_object) # printed in default formatThe output is:
<class 'datetime.date'>
2022-09-19Convert string to datetime.time() object example
The following example converts a time string to a datetime.time() object and prints the class type and value of the resulting object:
from datetime import datetime
time_str = '13::55::26'
time_object = datetime.strptime(time_str, '%H::%M::%S').time()
print(type(time_object))
print(time_object)The output is:
<class 'datetime.time'>
13:55:26Convert string to datetime.datetime() with local example
The following example converts a German local date string to a datetime.datetime() object and prints the class type and value of the resulting object:
from datetime import datetime
import locale
locale.setlocale(locale.LC_ALL, 'de_DE')
date_str_de_DE = '16-Dezember-2022 Freitag' # de_DE locale
datetime_object = datetime.strptime(date_str_de_DE, '%d-%B-%Y %A')
print(type(datetime_object))
print(datetime_object)The output is:
<class 'datetime.datetime'>
2022-12-16 00:00:00Note that the resulting object does not include the day of the week name from the input string, because the datetime.datetime() object includes the day of the week only as a decimal number.
Convert a string to a struct_time() object using time.strptime()
The syntax of the time.strptime() method is as follows:
time.strptime(time_string[, format])
The time.strptime() method returns a time.struct_time() object that corresponds to the time_string parsed by the format. Time_string is required and both arguments must be strings. If the format is not provided, the default is:
'%a %b %d %H:%M:%S %Y'
This matches the format returned by the ctime() function.
The format commands for time.strptime() and time.strftime() are the same.
Convert string to struct_time() object with the example format provided
The following example converts a time string into a time.struct_time() object by providing the format argument and prints the value of the resulting object:
import time
time_str = '11::33::54'
time_obj = time.strptime(time_str, '%H::%M::%S')
print("A time.struct_time object that uses the format provided:")
print(time_obj)The output is:
A time.struct_time object that uses the format provided:
time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1,
tm_hour=11, tm_min=33, tm_sec=54, tm_wday=0, tm_yday=1,
tm_isdst=-1)As shown in the output, when you convert a string to a time.struct_time() object, the strptime() method uses placeholder values for any format instructions that are not defined in the format argument.
Convert string to struct_time() object using default format
If you do not provide a format argument when converting a time string to a time.struct_time() object, the default format will be used and an error will occur if the input string does not exactly match the default format:
'%a %b %d %H:%M:%S %Y'
The following example converts a time string to a time.struct_time() object without any format arguments and prints the value of the resulting object:
import time
# default format - "%a %b %d %H:%M:%S %Y"
time_str_default = 'Mon Dec 12 14:55:02 2022'
time_obj_default = time.strptime(time_str_default)
print("A time.struct_time object that uses the default format:")
print(time_obj_default)The output is:
A time.struct_time object that uses the default format:
time.struct_time(tm_year=2022, tm_mon=12, tm_mday=12,
tm_hour=14, tm_min=55, tm_sec=2, tm_wday=0, tm_yday=346,
tm_isdst=-1)As shown in the output, when you convert a string to a time.struct_time() object, the strptime() method uses placeholder values for any format instructions that are not defined in the format argument or by default if no format is provided.
Troubleshooting strptime() errors.
If the input string cannot be parsed using the format provided by strptime(), a ValueError is raised. You can use a try block to test for parsing errors, along with an else block to print the results. The ValueError messages you receive when using the strptime() method clearly explain the main reasons for parsing errors. The following example shows some common errors, such as extra data and format mismatch:
from datetime import datetime
import time
datetime_str = '09/19/18 13:55:26'
try:
datetime_object = datetime.strptime(datetime_str, '%m/%d/%y')
except ValueError as ve1:
print('ValueError 1:', ve1)
time_str = '99::55::26'
try:
time_object = time.strptime(time_str, '%H::%M::%S')
except ValueError as ve2:
print('ValueError 2:', ve2)The output is:
ValueError 1: unconverted data remains: 13:55:26
ValueError 2: time data '99::55::26' does not match format '%H::%M::%S'Result
In this tutorial, you converted date and time strings into date and time objects using Python.









