Python strptime

The Python strptime is the shorter version of string to parse that helps you to parse string representation of dates and times into a datetime object. The dates and times are essential when working with data analysis or manipulation. So, we have to convert them from string type to datetime to analyze them further.

The Python strptime function is available in the datetime, pandas, and time modules. It accepts the string date as the first argument and the format specifiers as the second. Then, it converts the string to a datetime object.

This Python blog post will explore the strptime function, available formatting options, multiple examples, and handling ValueErrors. Some of the date and time formats we use in the regular work are:

  1. Date and Time Format Examples: yyyy-mm-dd hh:mm:ss or dd MMM yyyy hh:mm:ss AM/PM.
  2. Date only Format Examples: yyyy-mm-dd, dd MMM yyyy, dd/mm/yyyy, or mm/dd/yyyy.
  3. Time Only Format Examples: hh:mm:ss or hh:mm AM/PM.

Python datetime strptime

The Python module has the strptime function, which will accept the date and time strings and convert them into a datetime object. To use this function, we have to import the datetime module.

The syntax of the Python strptime function from the datetime module is as follows.

datetime.strptime(string_value, format) # format using directives

From the above syntax, the format parameter uses directives starting with the % symbol to indicate the formatting codes. The following is the list of available Python strptime directives. Remember, these are the same directives used in the strftime function to format dates and times.

  • %a – Short Version of Weekday (Wed)
  • %A – Full Version of Weekday (Wednesday)
  • %b – Short Version of Month Name (Jan)
  • %B – Full Version of Month Name (January)
  • %c – Local Version of Date and Time
  • %d – Day Number of a Month 01 to 31
  • %f – Microseconds 000000 to 999999
  • %H – Hours 00 to 23
  • %I – Hours 00 to 12
  • %j – Day Number of the Year 001 to 366
  • %m – Month as a Number 01 to 12
  • %M – Minutes from 00 to 59
  • %p – The Python strptime function returns AM or PM
  • %S – Seconds from 00 to 59
  • %U – Week Number of the Year from 00 to 53, where First Day of the Week = Sunday
  • %w – Weekday as a Number from 0 to 6, Where 0 = Sunday
  • %W – Week Number of the Year from 00 to 53, where First Day of the Week = Monday
  • %x – Local Version of Date (05/23/19)
  • %X – Local Version of Time (10:45:32)
  • %y – Short Version of Year (19)
  • %Y – Full Version of the Year (2019)
  • %z – UTC Offset
  • %Z – Timezone

Python strptime in datetime module Example

The strptime function parses the date and time string_value based on the format code (directives) and returns a datetime object. Let me show you a simple example to understand the syntax and explain the usage of this function.

from datetime import datetime

string_value = "2019-12-31 11:59:58"
dt_format = "%Y-%m-%d %H:%M:%S"

parsed_dt = datetime.strptime(string_value, dt_format)

print(parsed_dt)
2019-12-31 11:59:58

How strptime Works?

The first line of the program imports the datatime object from the datetime module.

from datetime import datetime

In the following two lines, we declared a string date & time and the matching format with directives.

The below statement uses the strptime function available in the datetime class and concert the string date & time to a datetime object.

parsed_dt = datetime.strptime(string_value, dt_format)

Python strptime to parse date string

The first statement function converts the given string date in Day/Month/Year format to the local version of DateTime, where time equals 00:00:00.

In the next two statements, we parse Day Number, Month Name, and Full Year to the Python strptime function and return the Date and Time.

from datetime import datetime as dm

dvalue = dm.strptime('30/12/18', '%d/%m/%y')

print(dvalue)

dt_string = '31 December 2018'
value = dm.strptime(dt_string, '%d %B %Y')
print(value)

dt_str = '31 December 17'
dt_value = dm.strptime(dt_str, '%d %B %y')
print(dt_value)
2018-12-30 00:00:00
2018-12-31 00:00:00
2017-12-31 00:00:00

Python strptime to parse or covert a time string

This example accepts the “11:45:58” time and parses the string time using the “%H:%M:%S” format. By default, the strptime function parse and returns both date and time. So, you have to explicitly use the time() function to call the potion of it. The first print statement in the code below returns the default date and parsed time: the second statement parse and returns only the time part.

from datetime import datetime as dt

strTime = "11:45:58"
parsed_time = dt.strptime(strTime, "%H:%M:%S")
print("Parsed DateTime:", parsed_time)
print("Parsed time:", parsed_time.time())
Parsed DateTime: 1900-01-01 11:45:58
Parsed time: 11:45:58

In the above example, we declared a time and displayed the same. However, if you want to parse only the time part, use the time() function in the datetime class.

from datetime import datetime as dt

dt_str = '10/05/18 23:59:58'
dt_value = dt.strptime(dt_str, '%d/%m/%y %H:%M:%S')
print("Parsed DateTime:", dt_value)
print("Parsed time:", dt_value.time())
Parsed DateTime: 2018-05-10 23:59:58
Parsed time: 23:59:58

Parsing Date and Time string

Let me use this Python strptime to return the DateTime from the given string representation of day Number, Month, Year, Hours, Minutes, and Seconds.

from datetime import datetime as stp
 
dt_str = '31/12/18 23:59:58'
dt_value = stp.strptime(dt_str, '%d/%m/%y %H:%M:%S')
print(dt_value)
 
dt_str2 = '10-12-2017 19:12:58'
dt_value2 = stp.strptime(dt_str2, '%d-%m-%Y %H:%M:%S')
print(dt_value2)

Print Date and Time from given Hours, Minutes, and Seconds using this function. Please refer to the strftime in Python.

Python strptime Example

Python strptime to Convert List of Date and Time strings

In this example, we declared a string data type list of dates and times. The for loop iterates each date, and the strptime will convert them to datetime objects.

from datetime import datetime

data = ["10/05/16 01:10:8.030", "12/06/17 10:30:8.110",
    "15/07/18 22:19:5.9478", "30/08/19 10:11:6.045",
    "22/09/20 14:11:6.054"]

formatInfo = "%d/%m/%y %H:%M:%S.%f"

for i in data:
  print(datetime.strptime(i, formatInfo))
2016-05-10 01:10:08.030000
2017-06-12 10:30:08.110000
2018-07-15 22:19:05.947800
2019-08-30 10:11:06.045000
2020-09-22 14:11:06.054000

Parse string with AM/PM Indicator

The %p directive below helps the Python strptime function parse the PM indicator. You can replace PM with AM and check the result.

from datetime import datetime

str_time = "10:45 PM"
res = datetime.strptime(str_time, "%I:%M %p")
print("Parsed time:", res.time())
Parsed time: 22:45:00

Python strptime to convert string with timezone offset

While working with dates time zones play a significant role while working with dates because one mistake will change the date altogether. So, you have. Be very careful of using the correct format and check multiple times.

In this Python strptime example, we used the date, time, and timezone offset of five hours and thirty minutes, i.e., +0530. To parse the string with timezone, we used the %z directive.

If you observe the result, it has the parsed date, time, and timezone offset information.

from datetime import datetime

dt_str = "2019-12-31 12:30:42 +0530"
dt_format = "%Y-%m-%d %H:%M:%S %z"
dt_obj = datetime.strptime(dt_str, dt_format)
print("Parsed = ", dt_obj)
Parsed =  2019-12-31 12:30:42+05:30

Handling milliseconds in Python strptime

In Python, we can use the %f format specifier inside the datetime strptime function to parse or handle milliseconds.

from datetime import datetime

dt_str = "2022-05-13 09:30:00.123456"
dt_format = "%Y-%m-%d %H:%M:%S.%f"
res = datetime.strptime(dt_str, dt_format)
print("Result = ", res)
Result =  2022-05-13 09:30:00.123456

Python strptime function in the time module

Apart from the datetime library, the Python time module also provides the strptime function. Although it looks the same, we only use this function to work with time.

The strptime function in the time library accepts the string representation of a time as the first argument and the format specifier as the second. It uses both and converts it into a struct_time.

The syntax of the strptime function in the time module is as follows.

time.strptime(stringDt, format)

The format parameter uses the same directives mentioned in the datetime module.

strptime time module example

You can also utilize the time library to use this Python strptime function. In this time instance, we use it inside the time library.

import time
 
dvalue = time.strptime('31/12/18', '%d/%m/%y')
print(dvalue)
time.struct_time(tm_year=2018, tm_mon=12, tm_mday=31, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=365, tm_isdst=-1)

If you observe the above output, the Python strptime function returns the output as struct_time or a structured representation of time. You can use this struct_time to access each component further and manipulate it as required.

import time

dt = time.strptime('25/10/18', '%d/%m/%y')
print(dt)
print("day = ", dt.tm_mday)
print("Year = ", dt.tm_year)
time.struct_time(tm_year=2018, tm_mon=10, tm_mday=25, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=298, tm_isdst=-1)
day =  25
Year =  2018

Handling ValueErrors in strptime function

If the input time string does not match the format directives or if it has excess data even after parsing datetime, the Python strptime function will throw a ValueError.

In this example, we specify the abbreviates in the wrong order or use the wrong format to show you the error.

from datetime import datetime as rdm
 
dt_string = '31/12/18'
dval = rdm.strptime(dt_string, '%d %m %y')
 
print(dval)
ValueError: time data '31/12/18' does not match format '%d %m %y'

Python pandas strptime

When importing a CSV file into the DataFrame, most date and time columns are in string format. While performing the data analysis and manipulation, date columns play a vital role. We have to convert them back to a datetime object. We can use the strptime function provided by the Python pandas library or module in such cases.

As we want to explore the strptime function in this blog post, we mentioned it as the only option to handle date and time. However, the pandas library has many built-in functions for dates and times. For instance, pd.to_datetime() converts a string date automatically to a Timestamp object. You can use the format argument to specify the string format.