Skip to content

Instantly share code, notes, and snippets.

@Shide
Created May 21, 2020 08:38
Show Gist options
  • Save Shide/5b136f230fe5ba90679565a630e76d50 to your computer and use it in GitHub Desktop.
Save Shide/5b136f230fe5ba90679565a630e76d50 to your computer and use it in GitHub Desktop.
Changing timezones
import pytz
from datetime import datetime
other_tz = pytz.timezone('Europe/Madrid')
# From random aware datetime...
aware_datetime = datetime.utcnow().astimezone(other_tz)
# 1. Change aware datetime to UTC and remove tzinfo to obtain an unaware datetime
unaware_datetime = aware_datetime.astimezone(pytz.UTC).replace(tzinfo=None)
# 2. Set tzinfo to UTC directly on an unaware datetime to obtain an utc aware datetime
aware_datetime_utc = unaware_datetime.replace(tzinfo=pytz.UTC)
# 3. Convert the aware utc datetime into another timezone
reconverted_aware_datetime = aware_datetime_utc.astimezone(other_tz)
# Initial Aware Datetime and Reconverted Aware Datetime are equal
print(aware_datetime1 == aware_datetime2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment