Skip to content

Instantly share code, notes, and snippets.

@nicc777
Last active April 6, 2024 11:57
Show Gist options
  • Save nicc777/b0f5e4af9b01d8b05fd4ae4816d11d8b to your computer and use it in GitHub Desktop.
Save nicc777/b0f5e4af9b01d8b05fd4ae4816d11d8b to your computer and use it in GitHub Desktop.
Python Datetime Changes for UTC from 3.12

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment