To convert a string of this format to a Python date object:
In [1]: import datetime In [2]: t = "2015-01-30" In [3]: d = datetime.date(*(int(s) for s in t.split('-'))) In [4]: d Out[4]: datetime.date(2015, 1, 30)
To go to the last day of the next month:
In [4]: d Out[4]: datetime.date(2015, 1, 30) In [5]: new_month = (d.month + 1) if d.month != 12 else 1 In [6]: new_year = d.year if d.month != 12 else d.year + 1 In [7]: import calendar In [8]: new_day = calendar.monthrange(new_year, new_month)[1] In [9]: d = d.replace(year=new_year,month=new_month,day=new_day) In [10]: d Out[10]: datetime.date(2015, 2, 28)
And this datetime.date object can be easily converted to the string "YYYY-MM-DD":
In [11]: str(d) Out[11]: '2015-02-28'
EDIT:
To get the last business day (i.e. Monday through Friday) of the month:
In [8]: new_day = calendar.monthrange(new_year, new_month)[1] In [9]: d = d.replace(year=new_year,month=new_month,day=new_day) In [10]: day_of_the_week = d.isoweekday() In [11]: if day_of_the_week > 5: ....: adj_new_day = new_day - (day_of_the_week - 5) ....: d = d.replace(day=adj_new_day) ....: In [11]: d Out[11]: datetime.date(2015, 2, 27)
chucksmash
source share