如何在按月增加日期的同时获取月份的最后日期?

时间:2017-11-30 17:05:11

标签: python python-2.7

我有以下代码,可以按月增加。然而,在2月之后,每个月显示最后一天为28。如何在每月增加的同时获得每个月的实际最后一天。

from dateutil.relativedelta import relativedelta
import datetime
from datetime import date
import time

Start_Date = date(2010, 01, 01)
End_Date = date(2010, 01, 31)
Final_startdate = date(2011, 12, 01)

while Start_Date < Final_startdate:
    print Start_Date
    print End_Date

    Start_Date = Start_Date + relativedelta(months=+1)
    End_Date = End_Date + relativedelta(months=+1)

这就是我得到的:

2010-01-01

2010-01-31

2010-02-01

2010-02-28

2010-03-01

2010-03-28

2010-04-01

2010-04-28

2010-05-01

2010-05-28

2010-06-01

2010-06-28

2010-07-01

2010-07-28

2010-08-01

2010-08-28

1 个答案:

答案 0 :(得分:0)

我将end_date的最后一行代码更改为下面的代码并且它可以正常工作。我得到了我想要的答案。

End_Date = Start_Date + relativedelta(months=+1,days=-1)

我得到的答案是

2010-01-01

2010-01-31

2010-02-01

2010-02-28

2010-03-01

2010-03-31

2010-04-01

2010-04-30

2010-05-01

2010-05-31

2010-06-01

2010-06-30

2010-07-01

2010-07-31

2010-08-01