How can I convert 24 hour time to 12 hour time? How can I convert 24 hour time to 12 hour time? python-3.x python-3.x

How can I convert 24 hour time to 12 hour time?


>>> from datetime import datetime>>> d = datetime.strptime("10:30", "%H:%M")>>> d.strftime("%I:%M %p")'10:30 AM'>>> d = datetime.strptime("22:30", "%H:%M")>>> d.strftime("%I:%M %p")'10:30 PM'


The key to this code is to use the library function time.strptime() to parse the 24-hour string representations into a time.struct_time object, then use library function time.strftime() to format this struct_time into a string of your desired 12-hour format.

I'll assume you have no trouble writing a loop, to iterate through the values in the dict and to break the string into two substrings with one time value each.

For each substring, convert the time value with code like:

import timet = time.strptime(timevalue_24hour, "%H:%M")timevalue_12hour = time.strftime( "%I:%M %p", t )

The question, Converting string into datetime, also has helpful answers.


>>> from datetime import datetime>>> s = datetime.strptime("13:30", "%H:%M")>>> print(s.strftime("%r"))01:30:00 PM