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:

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.