Explain Codes LogoExplain Codes Logo

How do I get the current time?

python
datetime
pytz
utc
Nikita BarsukovbyNikita BarsukovΒ·Aug 4, 2024
⚑TLDR

For grabbing the current time in Python, look to datetime.now().time():

from datetime import datetime # I've got time on my side πŸ•’ print(datetime.now().time().strftime('%H:%M:%S'))

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:

from datetime import datetime, timezone # UTC, the Universal Time Coordin... ator? πŸ•— print(datetime.now(timezone.utc)) # UTC time

For the whole timezone shebang, use the pytz library:

from datetime import datetime import pytz # All around the world, the UTC stays the same! utc_time = datetime.now(pytz.utc) # Unless it's Eastern Time... eastern_time = utc_time.astimezone(pytz.timezone('US/Eastern')) # Let's see what the time is now print(eastern_time)

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

import time # 1970, a time of disco and Unix time inception πŸ’ƒπŸ•Ί print(time.time())

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:

now = datetime.now() # Royale with cheese: A formatted date-time πŸ” formatted_now = now.strftime('%Y-%m-%d %H:%M:%S') # All that formatted goodness print(formatted_now)

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():

    # The global meeting time, UTC ⌚ print(datetime.utcnow())
  • Localize your time using datetime and pytz:

    from pytz import timezone # Grab the Croissant! We are going to Paris πŸ₯ paris_tz = timezone('Europe/Paris') # Vive la France! The current time in Paris paris_time = datetime.now(paris_time) print(paris_time)

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:

    # Who needs a calendar anyway? πŸ“… print(datetime.now())
  • Convert to String:

    now = datetime.now() # Because Python doesn't speak human... yet β˜• print(str(now))
  • With ctime for a readable timestamp:

    # Finally, time I can understand! print(time.ctime())

These options ensure you keep tracking time and date together hassle-free!