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:
1 2 3 4 5 6 7 8 9 10 11 12 |
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.