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:

d.strftime("%I:%M")

%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!

4 Likes

Like so:

from datetime import datetime

now = 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'))
1 Like

I know I’m necroposting, but I found this to be helpful in figuring out how to add the times to the Basta Fazoolin’ project as time objects rather than integers, like 11 and 16.

Also, worth noting that you can get rid of the leading 0s in your time by formatting it the way that this post suggests.

P.S. The %p must be within the “” for it to work.