Iterating through a range of dates in Python

后端 未结 23 1336
醉酒成梦
醉酒成梦 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 04:47

    Pandas is great for time series in general, and has direct support for date ranges.

    import pandas as pd
    daterange = pd.date_range(start_date, end_date)
    

    You can then loop over the daterange to print the date:

    for single_date in daterange:
        print (single_date.strftime("%Y-%m-%d"))
    

    It also has lots of options to make life easier. For example if you only wanted weekdays, you would just swap in bdate_range. See http://pandas.pydata.org/pandas-docs/stable/timeseries.html#generating-ranges-of-timestamps

    The power of Pandas is really its dataframes, which support vectorized operations (much like numpy) that make operations across large quantities of data very fast and easy.

    EDIT: You could also completely skip the for loop and just print it directly, which is easier and more efficient:

    print(daterange)
    

提交回复
热议问题