我想编写一个向前看1年的函数,但可以接受某个月作为开始计算的日期。
例如,如果开始时间为1/1/2011
,则结束时间为1/1/2012
。新的开始时间为1/2/2011
,新的结束时间为1/2/2012
。开始和结束时间应该像这样前进。
这是我的尝试:
import datetime
from dateutil.relativedelta import relativedelta
from datetime import date
def Count(StartDate, EndDate,count):
#while StartDate < FinalDate:
count = 1
print (StartDate, EndDate)
StartDate = date(2011,01,01)
FinalDate = date (2014,01,01)
EndDate = StartDate + relativedelta(years=+1)
count = 1
a = Count(StartDate, EndDate,count)
print a
打印类似
的内容(datetime.date(2011, 2, 1), datetime.date(2012, 2, 1))
None
(datetime.date(2011, 3, 1), datetime.date(2012, 3, 1))
None
(datetime.date(2011, 4, 1), datetime.date(2012, 4, 1))
None
(datetime.date(2011, 5, 1), datetime.date(2012, 5, 1))
None
(datetime.date(2011, 6, 1), datetime.date(2012, 6, 1))
None
答案 0 :(得分:1)
from dateutil.relativedelta import relativedelta
new_date = old_date + relativedelta(years=1)
#you can use this for getting the 1 year later date
#or use
#adding to date
from datetime import datetime, timedelta
new_date = datetime.today()
new_date = new_date + timedelta(months=1)
new_date = new_date + timedelta(years=1)
答案 1 :(得分:1)
import datetime
from dateutil.relativedelta import relativedelta
from datetime import date
def Count(StartDate, EndDate,count):
#while StartDate < FinalDate:
count = 1
print (StartDate, EndDate)
StartDate = date(2011,01,01)
FinalDate = date (2014,01,01)
EndDate = StartDate + relativedelta(years=+1)
count = 1
while StartDate < FinalDate:
StartDate = StartDate + relativedelta(months=+1)
EndDate = StartDate + relativedelta(years=+1)
a = Count(StartDate, EndDate,count)
print a