strptime do parsing in dates on your behalf:
def firstofmonth(MmmYyyy): return datetime.datetime.strptime(MmmYyyy, '%b-%Y').date()
much better than messing with tokenization, regexp, and c! -).
To get the date of the last day of the month, you can really use the calendar module:
def lastofmonth(MmmYyyy): first = firstofmonth(MmmYyyy) _, lastday = calendar.monthrange(first.year, first.month) return datetime.date(first.year, first.month, lastday)
You could TOTALLY do it neatly with just a date-time, for example, a USER working approach:
def lastofmonth(MmmYyyy): first = firstofmonth(MmmYyyy) return first.replace(month=first.month+1, day=1 ) - datetime.timedelta(days=1)
but, alas!, it breaks into December, and the code necessary for the December case makes the general approach more dense than the calendar, -).
source share