Time-zone-aware datetime
Python datetimes are usually naive, which means they don't know which time zone they refer to. This can be a major problem because, given a datetime, it's impossible to know when it actually refers to.
The most common error in working with dates in Python is trying to get the current datetime through datetime.datetime.now()
, as all datetime
methods work with naive dates, it's impossible to know which time that value represents.
How to do it...
Perform the following steps for this recipe:
- The only reliable way to retrieve the current datetime is by using
datetime.datetime.utcnow()
. Independently of where the user is and how the system is configured, it will always return the UTC time. So we need to make it time-zone-aware to be able to decline it to any time zone in the world:
import datetime def now(): return datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
- Once we have a time-zone-aware current time, it is possible to convert it to any other time...