Facebook PageView

How to convert to 12 hour clock

Written by Parvatiandsons Team

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'

Example:-

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

 

  •     How to convert a date string to different format in Python.
  • Introduction of Django