Original blog: https://blog.miguelgrinberg.com/post/it-s-time-for-a-change-datetime-utcnow-is-now-deprecated
Example for new timezone aware objects:
from datetime import datetime, timezone
def aware_utcnow():
return datetime.now(timezone.utc)
def aware_utcfromtimestamp(timestamp):
return datetime.fromtimestamp(timestamp, timezone.utc)
def naive_utcnow():
return aware_utcnow().replace(tzinfo=None)
def naive_utcfromtimestamp(timestamp):
return aware_utcfromtimestamp(timestamp).replace(tzinfo=None)
print(aware_utcnow())
print(aware_utcfromtimestamp(0))
print(naive_utcnow())
print(naive_utcfromtimestamp(0))
Note
if you are using Python 3.11 or newer, you can replace datetime.timezone.utc with a shorter datetime.UTC.