3

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

我想在一个循环中步进这个日期,以便它提前到每个月的 1 号和 15 号。

所以datetime(2007, 2, 15)会一步一步来datetime(2007, 3, 1)

在下一次迭代中,它会逐步执行到datetime(2007, 3, 15)...然后到datetime(2007, 4, 1)等等。

是否有任何可能的方法来做到这一点,timedelta或者dateutils考虑到它必须逐步改变的天数,不断变化?

4

3 回答 3

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。

于 2013-10-09T19:24:00.877 回答
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 的解决方案都是有问题的。

于 2013-10-09T19:43:45.340 回答
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
于 2013-10-09T20:08:40.863 回答