Last active
April 17, 2018 13:04
-
-
Save joaodaher/b1f141e0bb573fd94fbe73239d667713 to your computer and use it in GitHub Desktop.
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 datetime import datetime | |
def _ordinal(day): | |
SUFFIX = { | |
1: 'st', | |
2: 'nd', | |
3: 'rd', | |
} | |
if day in [11, 12, 13]: | |
suffix = 'th' | |
else: | |
last_digit = int(str(day)[-1]) | |
suffix = SUFFIX.get(last_digit, 'th') | |
return '{day}{suffix}'.format(day=day, suffix=suffix) | |
def _hour_to_str(date): | |
return date.strftime('%-I %p') | |
def _str_to_date(date_str): | |
return datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%SZ") | |
def _month_str(days, month): | |
return '{days} {month}'.format( | |
days=', '.join(days), | |
month=month, | |
) | |
def humanizeTransmissionDates(datesAsStrings): | |
date_parts = [] | |
current_month = [] | |
month_parts = [] | |
for date_str in datesAsStrings: | |
dt = _str_to_date(date_str) | |
month = dt.strftime('%B') | |
day = _ordinal(dt.day) | |
if month == current_month: | |
month_parts.append(day) | |
else: | |
if current_month: | |
date_parts.append(_month_str(days=month_parts, month=current_month)) | |
month_parts = [day] | |
current_month = month | |
time_str = _hour_to_str(dt) | |
if date_parts: | |
humanized = '{all_months}, and '.format( | |
all_months=', '.join(date_parts), | |
) | |
else: | |
humanized = '' | |
humanized = '{humanized}{last_month} at {time_str}'.format( | |
humanized=humanized, | |
last_month=_month_str(days=month_parts, month=current_month), | |
time_str=time_str, | |
) | |
return humanized |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment