Generating all dates within a given range in python

前端 未结 9 553
青春惊慌失措
青春惊慌失措 2021-02-02 08:31

I have two string variables which contain dates in yyyy-mm-dd format as follows :

date1 = \'2011-05-03\'
date2 = \'2011-05-10\'

I want to write

相关标签:
9条回答
  • 2021-02-02 09:17

    Pandas is great for time series in general, and has direct support both for date ranges and date parsing (it's automagic).

    import pandas as pd
    date1 = '2011-05-03'
    date2 = '2011-05-10'
    mydates = pd.date_range(date1, date2).tolist()
    

    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 https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#generating-ranges-of-timestamps

    0 讨论(0)
  • 2021-02-02 09:17
    import datetime
    real_date1 = datetime.date(*[int(x) for x in date1.split('-')])
    real_date2 = datetime.date(*[int(x) for x in date2.split('-')])
    date_range =  real_date2 - real_date1
    dates = list()
    for days in xrange(date_range.days):
        dates.append(real_date1 + datetime.timedelta(days))
    
    print dates
    

    for python 3 use range instead of xrange.

    0 讨论(0)
  • 2021-02-02 09:22
    from dateutil import rrule, parser
    
    date1 = '2011-05-03'
    date2 = '2011-05-10'
    
    dates = list(rrule.rrule(rrule.DAILY,
                             dtstart=parser.parse(date1),
                             until=parser.parse(date2)))
    
    print dates
    

    Since dateutil is not a standard library, you will have to install it as a separate package. See the documentation for further details regarding the format (especially dayfirst and yearfirst switches).

    0 讨论(0)
提交回复
热议问题