So for today, we are going to discuss how we convert a string to datetime using the Python strptime() method.
Let us get started.
Python strptime() Method
The Python strptime()
method is available in both datetime
and time
modules. It is used to parse a given string into datetime or time object according to the specified format.
The use of this function is about the same for both the modules, the only difference being in the type of object returned. Let us have a closer look at the syntax for using it.
For the datetime module, the syntax for using the strptime()
method is given below.
datetime.strptime(date_string, format)
The above statement returns a datetime
object corresponding to date_string
parsed according to the specified format.
And for the time module, the syntax for using the strptime()
is fairly similar.
time.strptime(string[, format])
Here the method does the same job just here the returned value is a struct_time
object as returned by gmtime()
or localtime()
.
For both cases, the format parameter uses the same directives as those used by strftime() as given in the format table below. The format parameter has to be a string and has a default value "%a %b %d %H:%M:%S %Y"
. If the string cannot be parsed according to the given format, or if it has excess data after parsing, a ValueError
is raised.
Format Table
You must follow the below-given format table to use appropriate directives while specifying the format parameter.
Directive | Meaning of the Directive | Example Output |
---|---|---|
%A | Weekday as locale’s full name. | Wednesday |
%a | Weekday as locale’s abbreviated name. | Mon, Tue, Wed |
%w | Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. | 0,1,2,3,4…6 |
%d | Day of the month as a zero-padded decimal number. | 01,02,03…31 |
%-d | Day of the month as a decimal number. (Platform specific) | 1,2,3… |
%b | Month as locale’s abbreviated name. | Mar |
%B | Month as locale’s full name. | March |
%m | Month as a zero-padded decimal number. | 01,02…12 |
%-m | Month as a decimal number. (Platform specific) | 1,2,…12 |
%y | Year without century as a zero-padded decimal number. | 20(for 2020) |
%Y | Year with century as a decimal number. | 2020, 2021, etc. |
%H | Hour (24-hour clock) as a zero-padded decimal number. | 01, 02, … |
%-H | Hour (24-hour clock) as a decimal number. (Platform specific) | 1,2,3,… |
%I | Hour (12-hour clock) as a zero-padded decimal number. | 01, 02, 03, … |
%-I | Hour (12-hour clock) as a decimal number. (Platform specific) | 1, 2, 3 … |
%p | Locale’s equivalent of either AM or PM. | AM, PM |
%M | Minute as a zero-padded decimal number. | 01, 02, …59 |
%-M | Minute as a decimal number. (Platform specific) | 1,2,3,…59 |
%S | Second as a zero-padded decimal number. | 01, 02,…59 |
%-S | Second as a decimal number. (Platform specific) | 1, 2, …59 |
%f | Microsecond as a decimal number, zero-padded on the left. | 000000 |
%z | UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive). | (empty), +0000, -0400, +1030 |
%Z | Time zone name (empty string if the object is naive). | (empty), UTC, IST, CST |
%j | Day of the year as a zero-padded decimal number. | 1, 2, 3, … 366 |
%-j | Day of the year as a decimal number. (Platform specific) | 1, 2, 3, … 366 |
%U | Week number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0. | 1, 2, 3,… 53 |
%W | Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0. | 1, 2, 3,… 53 |
%c | Locale’s appropriate date and time representation. | Wed May 06 12:23:56 2020 |
%x | Locale’s appropriate date representation. | 05/06/20 |
%X | Locale’s appropriate time representation. | 12:23:56 |
%% | A literal ‘%’ character. | % |
Working with the strptime() Method
So now that we are familiar with the syntax of using the strptime()
method for both datetime and time modules, let us see how we can use it.
1. time.strptime()
In the example below, we are going to convert a given string into a time object.
import time
time_string = "06/05/2020 12:06:58"
obj = time.strptime(time_string, "%d/%m/%Y %H:%M:%S")
print(type(obj))
print(obj)
#parsing using default formatting: %a %b %d %H:%M:%S %Y
def_obj = time.strptime("Wed May 06 12:06:58 2020")
print(def_obj)
Output:
<class 'time.struct_time'>
time.struct_time(tm_year=2020, tm_mon=5, tm_mday=6, tm_hour=12, tm_min=6, tm_sec=58, tm_wday=2, tm_yday=127, tm_isdst=-1)
time.struct_time(tm_year=2020, tm_mon=5, tm_mday=6, tm_hour=12, tm_min=6, tm_sec=58, tm_wday=2, tm_yday=127, tm_isdst=-1)
Here, time_string
is the given string containing the corresponding time parameters. We parse this string using the strptime() function following the “%d/%m/%Y %H:%M:%S” format into the variable obj
. As expected obj is of type time.struct_time
.
Nextly, we have also parsed another string using the default formatting(without specifying the format parameter). As mentioned earlier in this case by default format is set to %a %b %d %H:%M:%S %Y
. This justifies the output.
2. datetime.strptime()
Now let us use the strptime()
method to convert a given string into a datetime object.
from datetime import datetime
dt_string = "06//05//2020 12:06:58"
obj = datetime.strptime(dt_string, "%d//%m//%Y %H:%M:%S")
print(type(obj))
print("DateTime object: ", obj)
print("Time object: ", obj.time())
print("Date object: ", obj.date())
Output:

As you can see from the output above, the dt_string
is successfully converted into a datetime object. We can also use the time()
and date()
functions over this object to get datetime.time and datetime.date objects respectively.
Let us look at another example where we take the date and time using the input() function from the user.
from datetime import datetime
dt_string = str(input("Enter date in dd:mm:yyyy format:"))
try:
obj = datetime.strptime(dt_string, "%d:%m:%Y")
print(obj)
print(obj.strftime("Date:%d Month:%m Year:%Y")) #strftime to format datetime obj
except ValueError as ex:
print("ValueError: ", ex)
Output:

In this example, we take the dt_string
as user input and convert it into a datetime object using the strptime()
method. Again we take this object and print it is our desired format using the strftime()
method.
What if we do not provide the strptime() method a string which matches to the specified format? In that case, a ValueError
is raised. Look at the output below(for the same code) where we do so.
Enter date in dd:mm:yyyy format:6/5/20
ValueError: time data '6/5/20' does not match format '%d:%m:%Y'
Summing Up
So we today learned about converting a string into various types in Python using the strptime()
method.
For any further questions related to the topic feel free to use the comments below.
References
- What is Python strftime() function?,
- Python time module,
- time strptime() – Python Documentation,
- datetime strptime() – Python Documentation.