Created
May 21, 2020 08:38
-
-
Save Shide/5b136f230fe5ba90679565a630e76d50 to your computer and use it in GitHub Desktop.
Changing timezones
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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