For some reporting, I need to print a human readable date string for the week covered by the report, using just the standard python module library. So the strings should look like:
Dec 29, 2013 - Jan 4, 2014
Jan 26 - Feb 1, 2014
Jan 19 - 25, 2014
Below is a script I threw together to achieve this. But is there a simpler way to do this?
from datetime import (datetime, date, timedelta)
def week_string(dt):
(year, week, weekday) = dt.isocalendar()
week_0 = dt - timedelta(days=weekday)
week_1 = dt + timedelta(days=(6-weekday))
month_0 = week_0.strftime("%b")
day_0 = week_0.strftime("%e").strip()
year_0 = week_0.strftime("%Y")
month_1 = week_1.strftime("%b")
day_1 = week_1.strftime("%e").strip()
year_1 = week_1.strftime("%Y")
if year_0 != year_1:
return "%s %s, %s - %s %s, %s" %(
month_0, day_0, year_0,
month_1, day_1, year_1)
elif month_0 != month_1:
return "%s %s - %s %s, %s" %(
month_0, day_0,
month_1, day_1, year_1)
else:
return "%s %s - %s, %s" %(
month_0, day_0, day_1, year_1)
print week_string(date(2013, 12, 30))
print week_string(date(2014, 01, 30))
print week_string(datetime.date(datetime.now()))
Since the report script is going to be shared with other people, I want to avoid adding dependencies on anything they'd need to install.
datetime
is part of the standard library, so they wouldn't need to install anything aside from basic Python – jonrsharpe Jan 24 '14 at 22:17