Skip to content

Instantly share code, notes, and snippets.

@ianjosephwilson
Created March 5, 2012 01:21
Show Gist options
  • Save ianjosephwilson/1975784 to your computer and use it in GitHub Desktop.
Save ianjosephwilson/1975784 to your computer and use it in GitHub Desktop.
def human_readable_datetime(dt):
right_now = datetime.now()
if right_now.year == dt.year:
if right_now.month == dt.month:
# Same day
if right_now.day == dt.day:
datetime_format = '%I:%M %p'
# Within 2 days.
elif right_now <= dt + timedelta(days=2) and \
right_now >= dt - timedelta(days=2):
datetime_format = '%a %I:%M %p'
# Within 7 days.
elif right_now <= dt + timedelta(days=7) and \
right_now >= dt - timedelta(days=7):
datetime_format = '%A %I %p'
# Same month.
else:
# TODO: Should this only be the day??
datetime_format = '%b %d'
# Same year.
else:
datetime_format = '%b %d'
else:
# Not this year.
datetime_format = '%b %d %Y'
return dt.strftime(datetime_format)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment