Nate Nate - 2 months ago 6
Python Question

Convert 12 hour time string into datetime or time

Ive been trying to use

time.strptime(string1,'%H:%M')
, with no success

How can I get the following:

Input Output
3:14AM -> 03:14
9:33PM -> 21:33
12:21AM -> 00:21
12:15PM -> 12:15

Answer

Use %I for 12 hour times and %p for the am or pm as follows:

from datetime import datetime

for t in ["3:14AM", "9:33PM", "12:21AM", "12:15PM"]:
    print datetime.strptime(t, '%I:%M%p').strftime("%H:%M")

Giving you the following output:

03:14
21:33
00:21
12:15 

The formats used are documented in strftime() and strptime() Behavior

Comments