Explain Codes LogoExplain Codes Logo

How do I get a value of datetime.today() in Python that is "timezone aware"?

python
datetime
timezone
utc
Anton ShumikhinbyAnton Shumikhin·Oct 13, 2024
TLDR

Meet your new friend pytz. For a timezone-aware datetime, you can directly usedatetime.now() alongside pytz:

from datetime import datetime import pytz # Just your usual "all aware" datetime aware_datetime = datetime.now(pytz.timezone("UTC")) print(aware_datetime) # Excuse me, what's the time?

Alter "UTC" with your favorite timezone, say "America/New_York", to get the current time accompanied by explicit timezone info.

Setting up UTC-aware datetime

When you find yourself continually working with UTC in Python, you can make use of datetime.utcnow().replace(tzinfo=pytz.utc) to get current UTC time:

from datetime import datetime import pytz # When you carry a little piece of UTC with you utc_aware_datetime = datetime.utcnow().replace(tzinfo=pytz.utc) print(utc_aware_datetime) # As universal as a cup of coffee.

Avoid ambiguity: Specify your timezone

You do not want to be that person who misses an all-important meeting because of a timezone snafu. Whenever you're working with specified timezones, remember to indicate that and spare yourself any confusion:

# No more guessing games with 'America/Los_Angeles' la_time = datetime.now(pytz.timezone('America/Los_Angeles')) print(la_time) # Hey LA! What's up?

Daylight saving time and Python

Life throws curveballs. So does Daylight Saving Time (DST). But, pytz and zoneinfo (Python 3.9+) can help you swing it right with the latest IANA time zone database:

from datetime import datetime, timezone from zoneinfo import ZoneInfo # Importing the future with Python 3.9+ # Reliable as your morning coffee with ZoneInfo pst_aware_datetime = datetime.now(ZoneInfo("America/Los_Angeles"))

Remember, mathematics and timezones do not mix. Stick to UTC for your arithmetic operations on datetime objects.

Size doesn't matter: Creating tzinfo classes

Creating a custom tzinfo class helps you keep consistent behavior across different platforms. Great things do come in small packages:

# Your very own tzinfo class: small, yet mighty.

Just Python things: Built-in timezone support

Celebrate the simplicity of Python 3.2+! With the built-in datetime.timezone.utc, you need no external libraries for timezone-aware datetime objects:

from datetime import datetime, timezone utc_aware_datetime = datetime.now(timezone.utc) print(utc_aware_datetime) # Lean, mean, and Python 3.2+ machine!

Visualization

Picture setting your clock (🕰️) to a global timezone (🌐):

Standard Clock Time (🕰️): 12:00 PM # Time is gold, but timezone is diamond.

Thanks to timezone info, your clock has a coordinate (🧭). Different city, same time:

from datetime import datetime import pytz # This clock understands timezones! aware_datetime = datetime.now(pytz.utc)

In an instant, it becomes:

Global Clock Time (🕰️🌐): 12:00 PM UTC # Who said time travel was impossible?

This is accuracy beyond space and time.

Tips, tricks, and pitfalls

  • Performance: Midnight can be tricky when working across timezones. Keep a close watch on your system's health.
  • Data management: Keep it cool with UTC in your databases. Local time? Convert as per your user's need.
  • Freshness: pytz and zoneinfo thrive on fresh updates. You can choose to bring your timezone data up to date with the tzdata package.
  • User input: It's a user-input eat user-input world. Use exceptional parsing techniques and outline your timezone expectations clearly.
  • Leap seconds: Guess what! datetime doesn't know leap seconds. If your precision levels demand leap seconds, you might need different tools.