在Python中逐步完成日期

时间:2013-10-09 19:12:41

标签: python loops datetime python-dateutil

假设我的开始日期为datetime(2007, 2, 15)

我想在循环中执行此日期,以便将其提前到每个月的第1和第15个月。

因此datetime(2007, 2, 15)将步入datetime(2007, 3, 1)

在下一次迭代中,它将步入datetime(2007, 3, 15) ...然后转到datetime(2007, 4, 1),依此类推。

对于timedeltadateutils是否有任何可行的方法,考虑到它必须逐步改变的天数?

3 个答案:

答案 0 :(得分: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对象,但你可以根据需要使用datetime.date。

答案 1 :(得分: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的解决方案而出现问题。

答案 2 :(得分: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