Why does it display 24-hour time?

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.

7 Likes

Can you explain why some codes are capital letters while others are not?

1 Like

Directives may sometimes come in two forms, each with their own meaning.

%y  =>  00, 01, 02, 98, 99

%Y  =>  1900, 2000, 2019

A complete table of directives and their meanings is given on the documentation page.

2 Likes

Is this Greenwich Mean Time? The clock is 5 hours ahead of EST.

9 Likes

It seems to output Greenwich Mean Time.
How can I set it to a different time zone so that it displays the right time for my current location?

11 Likes

her we declare now as a variable but is an inbuilt function,how it diffirentiate between these two?

I’ve been searching on the original documentation, then on this article: A faster (and better) alternative to pytz | Blog | Pendulum - Python datetimes made easy, then here:
http://pytz.sourceforge.net/

And finally in two discussions on StackOverflow. We all have to remember that most of us are newbies and contrary to what pros say the documentation is something that is not friendly at all with the inexperienced user. Another bias is that most of the libraries work in Python 3. pytz as an example changes a lot with respect to 2.7 all through 3.8.

I don’t have idea how it works. I know that in your local IDLE it will display alright but I also want to know how it works here. I’ve also seen the discussions on Codecademy without a proper solution;

Last but not least in this last thread the godfather mtf do not answers properly to the question and the other mod surprisingly closes the thread. I hope some cool guy or moderator answers this question. I will continue the class but I feel a bit sad as I haven’t answered this question.

I’m pretty much convinced there’s an answer out there (even the links I have shared could contain that information). The thing is that as a newbie I do not understand most of the things that are said in this links. I hope y’all have a nice day :pensive:

1 Like

Because 24HR time is better, simpler, and less ambigious

2 Likes