How to convert to 12 hour clock


When getting the time, it is displayed as 24 hours, how do you get it to print to the console in 12 hours instead?


i think you have to modify the datatime in the library of python...or there is another package...good question..but i dk


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.

For example, say it is currently 6:56 PM. Your code would initially look like this:

 from datetime import datetime
 d = datetime.strptime("6:56", "%H:%M")

When you use the "strptime" method, you are parsing the string "6:56" into values of hours and minutes to create a time object, d. This will give you 18:56, the 24-hour version. Now for the 12-hour:


%I is a directive that tells Python to give the hour in the 12-hour format. Additionally, you may include the %p directive which will display "AM" or "PM".

d.strftime("%I:%M" %p)
'6:56 PM'

Hope this answered your question!


Like so:

from datetime import datetime

now =
#24-hour format
print(now.strftime('%Y/%m/%d %H:%M:%S'))
#12-hour format
print(now.strftime('%Y/%m/%d %I:%M:%S'))