Skip to content
Advertisement

convert 24 hour time (in string format) to time format

The time is given in string for eg “23:20”. However in my function I need to compare times for which I gotta convert these to time format

I tried strptime() and it works with 12 hour format for eg when I enter “12:00PM”

Advertisement

Answer

For converting 24 hour format to a datetime.time object you need to use the %H (hours in 24h format) and %M (minutes) format:

import datetime as dt

string_time = "23:20"
out_time = dt.datetime.strptime(string_time, r"%H:%M")
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement