Iterating through a range of dates in Python

后端 未结 23 1596
醉酒成梦
醉酒成梦 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条回答
  •  萌比男神i
    2020-11-22 04:58

    Numpy's arange function can be applied to dates:

    import numpy as np
    from datetime import datetime, timedelta
    d0 = datetime(2009, 1,1)
    d1 = datetime(2010, 1,1)
    dt = timedelta(days = 1)
    dates = np.arange(d0, d1, dt).astype(datetime)
    

    The use of astype is to convert from numpy.datetime64 to an array of datetime.datetime objects.

提交回复
热议问题