Iterating through a range of dates in Python

后端 未结 23 1778
醉酒成梦
醉酒成梦 2020-11-22 04:40

I have the following code to do this, but how can I do it better? Right now I think it\'s better than nested loops, but it starts to get Perl-one-linerish when you have a ge

23条回答
  •  佛祖请我去吃肉
    2020-11-22 05:06

    Why not try:

    import datetime as dt
    
    start_date = dt.datetime(2012, 12,1)
    end_date = dt.datetime(2012, 12,5)
    
    total_days = (end_date - start_date).days + 1 #inclusive 5 days
    
    for day_number in range(total_days):
        current_date = (start_date + dt.timedelta(days = day_number)).date()
        print current_date
    

提交回复
热议问题