barker/barker/barker/models/tzinfoutc.py

47 lines
1005 B
Python

from datetime import timedelta, tzinfo, datetime
ZERO = timedelta(0)
HOUR = timedelta(hours=1)
# A UTC class.
class UTC(tzinfo):
"""UTC"""
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return ZERO
utc = UTC()
def get_age(old_date, now=None):
def is_naive(date):
return date.tzinfo is None or date.tzinfo.utcoffset(date) is None
if now is None:
now = datetime.utcnow().replace(tzinfo=utc)
if is_naive(old_date) == is_naive(now):
pass
elif is_naive(old_date):
old_date = old_date.replace(tzinfo=utc)
else:
now = now.replace(tzinfo=utc)
delta = now - old_date
if delta.days > 0:
return "{0} days".format(delta.days)
if delta.seconds > 3600:
return "{0} hours".format(delta.seconds // 3600)
if delta.seconds > 60:
return "{0} minutes".format(delta.seconds // 60)
return "{0} seconds".format(delta.seconds)