How do I get the current time?
For grabbing the current time in Python, look to datetime.now().time()
:
There you go! The time in HH:MM:SS format. Direct and to-the-point.
Time zones like a Pro
datetime.now()
defaults to your local time. However, you might be juggling UTC or other time zones:
For the whole timezone shebang, use the pytz
library:
Avoid unnecessary time zone confusion with the pytz
library.
Time traveled gap, aka Unix Epoch time
If you wish to time travel or work with Unix Epoch format (seconds since the infamous January 1, 1970):
Useful when dealing with systems that love a good old Epoch format.
Format that stamp!
When you need a user-friendly, beautifully formatted time or want your logs to look as uniform as Buckingham Palace guards, say hello to strftime
:
Customize your timeframe using the rules found at strftime.org.
Global Citizen? Meet UTC and localization
Time zones are a nuisance when your app has users basking in different sunlight:
-
To secure the current UTC time, fetch
datetime.utcnow()
: -
Localize your time using
datetime
andpytz
:
No more night calls with this simple approach!
Date Time Tandem
Often, it's a duo. You need both the date and time. Python can help:
-
Current Date-Time:
-
Convert to String:
-
With
ctime
for a readable timestamp:
These options ensure you keep tracking time and date together hassle-free!
Was this article helpful?