Why does it display 24-hour time?


#1

Question

Why does it display 24-hour time?

Answer

The default format displayed will be 24-hour time, which isn’t what everyone prefers to read. If you want to change this, we’re going to have to use some code we haven’t seen before, but that’s okay! All code is new until we use it and learn it. Take a look at the code below and then I’ll explain how it works:

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

We use strftime() to explicitly format the date. The codes we use are Y, m, d, H, M, S, and I. For a full understanding of all the available formatting codes you can pass to strftime(), take a look at the documentation.
In short, we use %I to use a 12-hour clock, and the rest match the first letter of what they format.


FAQ: Learn Python - Date and Time - Getting the Current Date and Time