将那种格式的字符串转换为Python日期对象:
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)
要前进到下个月的最后一天,请使用以下代码:
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)
这个 datetime.date
对象可以很容易地转换为一个 'YYYY-MM-DD' 字符串:
In [11]: str(d)
Out[11]: '2015-02-28'
编辑:
获取月份中的最后一个工作日(即周一至周五):
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)
datetime.datetime.strptime(string, "%Y-%m-%d").date()
。 - Flimmdate.fromisoformat('2019-12-04')
(文档) - Flimm