How to get date range at now to end of the month?
我使用日期时间,我有:
1 | delta = ((datetime.date.today() + datetime.timedelta(days=1)) - datetime.timedelta(???)).isoformat() |
我需要替换????从今天到月底。
怎么做?
要计算当前月的结束日期,请取当前月的第一个月,加上1个月,减去1天。例如,对于9月28日,您将以
1 2 | 1 September + 1 month = 1 October 1 October - 1 day = 30 September. |
1 2 3 4 5 | import datetime d = datetime.date(2013,12,8) last_day = datetime.date(d.year, (d.month+1)%12, 1) - datetime.timedelta(1,0,0) |
号
为了正确处理新年前后的约会,我发现dateutil.relativedelta是更好的选择。
另请参见如何在python中增加datetime month。
1 2 3 4 5 6 | import datetime from dateutil.relativedelta import relativedelta d = datetime.date(2013,12,8) last_day = datetime.date(d.year, d.month, 1)+relativedelta(months=1, days=-1) |