Created
February 23, 2015 08:31
-
-
Save chebee7i/a3bd2f14296a975b2af3 to your computer and use it in GitHub Desktop.
Naive and Aware Datetime Deltas
This file contains hidden or 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
from __future__ import print_function | |
import datetime | |
import pytz | |
paris = pytz.timezone('Europe/Paris') | |
utc = pytz.utc | |
before_naive = datetime.datetime(2013, 3, 31, 1, 59) | |
before_paris = paris.localize(before_naive) | |
before_utc = before_paris.astimezone(utc) | |
delta = datetime.timedelta(minutes=1) | |
after_utc = (before_utc + delta) | |
after_paris = after_utc.astimezone(paris) | |
# Compute aware deltas | |
minutes_paris = (after_paris - before_paris).total_seconds() / 60 | |
minutes_utc = (after_utc - before_utc).total_seconds() / 60 | |
# Compute naive deltas | |
naive_minutes_paris = (after_paris.replace(tzinfo=None) - before_paris.replace(tzinfo=None)).total_seconds() / 60 | |
naive_minutes_utc = (after_utc.replace(tzinfo=None) - before_utc.replace(tzinfo=None)).total_seconds() / 60 | |
print("Paris") | |
print(before_paris) | |
print(after_paris) | |
print("Minutes:", minutes_paris) # 1 minute, as expected | |
print("Naive Minutes:", naive_minutes_paris) # 61 minutes, as visually seen. | |
print() | |
print("UTC") | |
print(before_utc) | |
print(after_utc) | |
print("Minutes:", minutes_utc) # 1 minute, as expected. | |
print("Naive Minutes:", naive_minutes_utc) # 1 minute, as visually seen. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment