Beginners in Python
Web developers
And anyone else!
Datetime is heavily used
Nuances are not very obvious from the beginning
Share my own experiences
from datetime import datetime
naive = datetime.now()
print naive
import pytz
aware = datetime.now(pytz.utc)
print aware
print naive
ist = pytz.timezone('Asia/Kolkata')
aware = ist.localize(naive)
print aware
print aware.astimezone(pytz.utc)
utc_now = datetime.now(pytz.utc)
print utc_now
stupid_date_in_ist = utc_now.replace(tzinfo=ist)
print stupid_date_in_ist
print stupid_date_in_ist.utcoffset()
intelligent_date_in_ist = utc_now.astimezone(ist)
print intelligent_date_in_ist
print intelligent_date_in_ist.utcoffset()
old_date = datetime(year=1900, month=1, day=1, tzinfo=pytz.utc)
print old_date
intelligent_date_in_ist = old_date.astimezone(ist)
print intelligent_date_in_ist
print intelligent_date_in_ist.utcoffset()
from freezegun import freeze_time
# As a context manager
with freeze_time('2010-1-1'):
print datetime.now()
# As a decorator
@freeze_time('2010-1-1')
def go_back_in_time():
print datetime.now()
go_back_in_time()
@freeze_time('2010-1-1')
class A(object):
def time(self):
print datetime.now()
A().time()
# A method that expires all keys older than 30 days.
def expire_keys_older_than_30_days():
limit = datetime.now(pytz.utc) - timedelta(days=30)
old_keys = AccessKey.objects.filter(created_at__lte=limit)
old_keys.update(expired=True)
from django.test import TestCase
class TestDeleteOlderKeys(TestCase):
def test_expire_keys_older_than_30_days(self):
with freeze_time('2015-1-1 00:00:00+00:00'):
AccessKey.objects.create()
with freeze_time('2015-1-31 00:00:00+00:00'):
AccessKey.objects.create()
live_keys = AccessKey.objects.filter(expired=False)
self.assertEqual(live_keys.count(), 2)
with freeze_time('2015-3-1 00:00:00+00:00'):
expire_keys_older_than_30_days()
live_keys = AccessKey.objects.filter(expired=False)
self.assertEqual(live_keys.count(), 1)
from datetime import timedelta
date = datetime.now(pytz.utc)
print date
print date - timedelta(weeks=2)
print date - timedelta(days=2)
print date
from dateutil.relativedelta import relativedelta
print date - relativedelta(years=2, months=6)
from dateutil.parser import parse
print parse('2015-1-1')
print parse('2015')
print parse('2015-10-04 10:00:00+05:30')
print parse('2015-10-04 10:00:00+00:30')