Python strptime() – How to convert String to Date Time?

In this Python article, we will discuss the use of strptime function, and how to use this to convert string to a datetime object. We will also discuss various examples to understand the concept better. Let’s get started.

1. What is the use of datetime strptime in Python?

We use the function or method strptime() to convert a provided string into a DateTime object. The condition is that the string should be a valid representation of datetime.

The datetime.strptime() function intakes a time signifying string in different formats; a struct_time is returned in either gmtime() format or localtime() format.

The strptime takes the parameter similar to directives used by strftime function. The default format is “%a %b %d %H:%M:%S %Y”, its formatting is the same that is returned by ctime().

When the provided string format is invalid or when the parsed value has too much data then ValueError is thrown.

Syntax:
time.strptime(string[, format])
#or
datetime.strptime(date_string, format)

Parameters

  • string − The input time string which is parsed and converted to the object.
  • format − To parse the provided string, format directive is used.

According to the provided string and format code, the strptime() function returns an equivalent datetime object.


2. Different format Code List

DirectiveSpecificationOutput
%aused for an abbreviated name for weekdaysSun, Mon, …, Sat
%Aused for the full name of a weekdaySunday, Monday, …, Saturday
%wused to represent the weekday in whole numbers with 0 as of Sunday and 6 as of Saturday and other values in between as different weekdays.0, 1, 2, 3, 4, 5, 6
%dused to represent the day of a month in a zero-padded number way.01, 02, …, 31
%bused to represent the abbreviated name for the month.Jan, Feb, …, Dec
%Bused to represent the full name for the month.January, February, …, December
%mused to represent the month in a zero-padded number way.01, 02 … 12
%yused to represent a specific year as a zero-padded decimal number without displaying the century.01, 02, … 99
%Yused to represent a specific year as a decimal number with displaying the century.0001, 0002, … , 9999
%Hused to represent the hour in the 24-hour clock format in a zero-padded decimal number way.01, 02, … , 23
%Iused to represent the hour in the 12-hour clock format in a zero-padded decimal number way.01, 02, … , 12
%pused to represent AM or PM.AM, PM (en_US)
%Mused to represent the minute in a zero-padded decimal number way.01, 02, … , 59
%Sused to represent the second in a zero-padded decimal number way.01, 02, … , 59
%fused to represent the Microsecond in a zero-padded decimal number way to its left.000000, 000001, …, 999999
Not applicable with time module.
%zused to represent the ±HHMM[SS] calculated from the UTC according to the local time. (naive object returns an empty string).(empty), +0000, -0400, +1030
%Zused to represent the name of the time zone.(empty), UTC, IST, CST
%jused to represent the particular day of the year in a zero-padded decimal number way.001, 002, …, 366
%Uused to represent the particular week number of the year in a zero-padded decimal number way.
After a new year, days after the first Sunday are marked to be in week 0.
00, 01, …, 53
%Wused to represent the particular week number of the year in a zero-padded decimal number way.
After a new year, days after the first Monday are marked to be in week 0.
00, 01, …, 53
%cused to represent the local appropriate date and time.Tue Aug 16 21:30:00 1988
%xused to represent the local appropriate date.08/16/88 (None)
08/16/1988
%Xused to represent the local appropriate time.21:30:00
%%used to represent a “%” character as a literal.%
List of all useful formats for strptime function

3. datetime.strptime examples in Python

Let’s take some examples in different programs to see how to use them.

import datetime

provided_datetime_string_1 = "05/07/2021 12:15:32"

f1 = datetime.datetime.strptime(provided_datetime_string_1, "%d/%m/%Y %H:%M:%S")
print("format1 =", f1)

f2 = datetime.datetime.strptime(provided_datetime_string_1, "%m/%d/%Y %H:%M:%S")
print("format2 =", f2)
Output
format1 = 2021-07-05 12:15:32
format2 = 2021-05-07 12:15:32
import time
print(time.strptime('Fri Jul 05 13:01:02 2021'))
Output
time.struct_time(tm_year=2021, tm_mon=7, tm_mday=5, tm_hour=13, tm_min=1, tm_sec=2, tm_wday=4, tm_yday=186, tm_isdst=-1)
import datetime

string = '12::17::39'
f1 = datetime.datetime.strptime(string, '%H::%M::%S').time()
print(type(f1))
print(f1)
Output
12:17:39

3. ValueError in datetime strptime()

When the string provided by the user and the prescribed format code in the strptime() function doesn’t match then an error is generated which is ValueError.

Read more about errors and error handling in Python

import datetime

string = '12::two minutes::39'
f1 = datetime.datetime.strptime(string, '%H::%M::%S').time()
print(f1)
Output
Traceback (most recent call last):
File "main.py", line 4, in 
f1 = datetime.datetime.strptime(string, '%H::%M::%S').time()
File "/usr/lib/python3.4/_strptime.py", line 337, in _strptime
(data_string, format))
ValueError: time data '12::two minutes::39' does not match format '%H::%M::%S'

We can remove such errors using exception handling by catching the exception and correcting it.

Let’s do it on one other example. Try the above yourself after watching one.

import datetime
import time

input_string_1 = '07/2021/05 12:45:49'

try:
  object1 = datetime.datetime.strptime(input_string_1, '%m/%d/%y')
except ValueError as exception:
  print('Error Raised: ', exception)

input_string_2 = '99::55::26'

try:
  object2 = time.strptime(input_string_2, '%H::%M::%S')
except ValueError as exception:
  print('Error Raised: ', exception)
Output
Error Raised:  time data '07/2021/05 12:45:49' does not match format '%m/%d/%y'
Error Raised:  time data '99::55::26' does not match format '%H::%M::%S'

4. Conclusion

Finally, if we sum up, in this article we learned everything about the strptime function/method. We covered how to use and why to use the strptime function for milliseconds and different input formats, we also covered:

  • What is the use of Strptime in python and how to use the strptime in python
  • Different format Code List for the strptime function/method
  • ValueError in strptime() and how to remove the valueerror in strptime() fucntion

Read More: We recommend going through another article to convert a datetime object to formatted string using strftime()


Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Index