2013-10-09 41 views
3

假设我的开始日期为datetime(2007, 2, 15)在Python中逐步完成日期

我想在一个循环中加入这个日期,以便它进入每个月的第1天和第15天。

所以datetime(2007, 2, 15)将步骤datetime(2007, 3, 1)

在下一次迭代中,它将进入datetime(2007, 3, 15) ...然后到datetime(2007, 4, 1)等等。

是否有任何可能的方式来与timedeltadateutils做到这一点,考虑到,它必须经过的天数不断变化?

回答

2
from datetime import datetime 
for m in range(1, 13): 
    for d in (1, 15): 
     print str(datetime(2013, m, d)) 

2013-01-01 00:00:00 
2013-01-15 00:00:00 
2013-02-01 00:00:00 
2013-02-15 00:00:00 
2013-03-01 00:00:00 
2013-03-15 00:00:00 
2013-04-01 00:00:00 
2013-04-15 00:00:00 
2013-05-01 00:00:00 
2013-05-15 00:00:00 
2013-06-01 00:00:00 
2013-06-15 00:00:00 
2013-07-01 00:00:00 
2013-07-15 00:00:00 
2013-08-01 00:00:00 
2013-08-15 00:00:00 
2013-09-01 00:00:00 
2013-09-15 00:00:00 
2013-10-01 00:00:00 
2013-10-15 00:00:00 
2013-11-01 00:00:00 
2013-11-15 00:00:00 
2013-12-01 00:00:00 
2013-12-15 00:00:00 

我倾向于使用日期时间超过日期对象,但您可以根据您的需要使用datetime.date。

1

我会遍历每一天,而忽略其中每月天数不为1或15例任何日期:

import datetime 

current_time = datetime.datetime(2007,2,15) 
end_time = datetime.datetime(2008,4,1) 

while current_time <= end_time: 
    if current_time.day in [1,15]: 
    print(current_time) 
    current_time += datetime.timedelta(days=1) 

这样,您就可以在多个迭代年开始在15个,这两个问题都会在doog的解决方案中出现问题。

0
from datetime import datetime  
d = datetime(month=2,year=2007,day=15)  
current_day = next_day = d.day 
current_month = next_month = d.month 
current_year = next_year = d.year 
for i in range(25): 
    if current_day == 1: 
     next_day = 15 
    elif current_day == 15: 
     next_day = 1 
     if current_month == 12: 
      next_month = 1 
      next_year+=1 
     else: 
      next_month+=1  
    new_date=datetime(month=next_month,year=next_year,day=next_day) 
    print new_date 
    current_day,current_month,current_year=next_day,next_month,next_year 

2007-03-01 00:00:00 
2007-03-15 00:00:00 
2007-04-01 00:00:00 
2007-04-15 00:00:00 
2007-05-01 00:00:00 
2007-05-15 00:00:00 
2007-06-01 00:00:00 
2007-06-15 00:00:00 
2007-07-01 00:00:00 
2007-07-15 00:00:00 
2007-08-01 00:00:00 
2007-08-15 00:00:00 
2007-09-01 00:00:00 
2007-09-15 00:00:00 
2007-10-01 00:00:00 
2007-10-15 00:00:00 
2007-11-01 00:00:00 
2007-11-15 00:00:00 
2007-12-01 00:00:00 
2007-12-15 00:00:00 
2008-01-01 00:00:00 
2008-01-15 00:00:00 
2008-02-01 00:00:00 
2008-02-15 00:00:00 
2008-03-01 00:00:00