The time.strptime()function converts a string representing time/date to a struct_time object. struct_time is a data structure defined in the time module, used to represent date and time information.

Syntax:
strptime(string, format = None)
copy
string A required string representation of the timestamp to be converted to struct_time
format An optional string detailing the format of the  string. 
Parameters:

The function returns the struct_time object representing the input time.

If the format is not given, the function will assume the default format,  '%a %b %d %H:%M:%S %Y' e.g Wed Feb 19 16:48:17 2020 .

ExampleEdit & Run

Using the strptime() function.

#import time module
import time

date = 'Wed Aug  9 05:50:54 2023'

#Convert the time to a struct_time object
time_obj = time.strptime(date)

print(time_obj)
copy
Output:
time.struct_time(tm_year=2023, tm_mon=8, tm_mday=9, tm_hour=5, tm_min=50, tm_sec=54, tm_wday=2, tm_yday=221, tm_isdst=-1) [Finished in 0.021037720143795013s]

The time.ctime() function converts seconds representing a timestamp since the epoch to a string formatted similarly to the default format.

ExampleEdit & Run
import time

today = time.ctime()
print(today, end = '\n')

print(time.strptime(today))
copy
Output:
Mon Jan 20 03:10:22 2025 time.struct_time(tm_year=2025, tm_mon=1, tm_mday=20, tm_hour=3, tm_min=10, tm_sec=22, tm_wday=0, tm_yday=20, tm_isdst=-1) [Finished in 0.02018425054848194s]

with a custom format

We can use the format parameter to indicate to the strptime() function how the input time is presented The format parameter is a string that contains formatting codes that indicate for example,  if the date is presented as  "YYYY-MM-DD HH:MM:SS" then the format string should be "%Y-%m-%d %H:%M:%S".

ExampleEdit & Run

using a custom format

import time

date = "14-3-2018 14:30:00"

format_string = "%d-%m-%Y %H:%M:%S"

time_obj = time.strptime(date, format_string)
print(time_obj)
copy
Output:
time.struct_time(tm_year=2018, tm_mon=3, tm_mday=14, tm_hour=14, tm_min=30, tm_sec=0, tm_wday=2, tm_yday=73, tm_isdst=-1) [Finished in 0.02003325242549181s]
ExampleEdit & Run
import time

date = "July 6, 2023 13:30"

format_string = "%B %d, %Y %H:%M"

time_obj = time.strptime(date, format_string)

print(time_obj)
copy
Output:
time.struct_time(tm_year=2023, tm_mon=7, tm_mday=6, tm_hour=13, tm_min=30, tm_sec=0, tm_wday=3, tm_yday=187, tm_isdst=-1) [Finished in 0.020331423729658127s]