To convert string to time in Python 3 follow these steps:
- Import the time module.
- Assign the result of the time function to a variable.
- Format the value with the strptime function.
- 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.