How to convert to 12 hour clock

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 thi…

  • Prakash
  • Dec. 14, 2021
Django Python

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'


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'))


Parvati And Sons
Phone: 9837994101
cash, check, invoice
G-10, J.K Tower, Janta Inter College Road, Opposite Chocolate Room
Rudrapur, Uttarakhand 263153