How to convert string to time in Python

To convert string to time in Python 3 follow these steps:

  1. Import the time module.
  2. Assign the result of the time function to a variable.
  3. Format the value with the strptime function.
  4. Specify whether you want to display 12 or 24-hour format.

Let’s run the following code:

import time

def convert(time_string):
    date_var = time.strptime(time_string, '%I:%M%p')

    return date_var

my_time = convert('10:07PM')

print(my_time.tm_hour)
print(my_time.tm_min)
print(my_time.tm_sec)

Let’s run the code:

22
7
0

As a result, we have an hour, minute, and second. Inside the convert function, I used “%I”, instead of “%H” to convert 10 PM to 22.

Minutes equals 7 and seconds 0 because there are no seconds inside our string.

Now, you can use each value separately as a time object.