Created
September 17, 2015 23:10
-
-
Save mapsam/1f9e7efc653fd117d100 to your computer and use it in GitHub Desktop.
turn times into readable strings
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
def days_from_today(field): | |
'''Takes a python date object and returns days from today | |
''' | |
if isinstance(field, datetime.date): | |
return ( | |
datetime.date(field.year, field.month, field.day) - | |
datetime.date.today() | |
).days | |
elif isinstance(field, datetime.datetime): | |
field = field.replace(tzinfo=pytz.utc) | |
return ( | |
datetime.datetime(field.year, field.month, field.day) - | |
datetime.datetime.now(pytz.utc) | |
).days | |
else: | |
return field | |
def format_days_from_today(field): | |
'''Uses days_from_today to build readable "X days ago" | |
''' | |
days = days_from_today(field) | |
if days == 0: | |
return 'Today' | |
elif days == 1: | |
return '{} day from now'.format(abs(days)) | |
elif days > 1: | |
return '{} days from now'.format(abs(days)) | |
elif days == -1: | |
return '{} day ago'.format(abs(days)) | |
else: | |
return '{} days ago'.format(abs(days)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment