Creating a range of dates in Python

后端 未结 20 2083
栀梦
栀梦 2020-11-22 11:02

I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this?

相关标签:
20条回答
  • 2020-11-22 11:25

    From the title of this question I was expecting to find something like range(), that would let me specify two dates and create a list with all the dates in between. That way one does not need to calculate the number of days between those two dates, if one does not know it beforehand.

    So with the risk of being slightly off-topic, this one-liner does the job:

    import datetime
    start_date = datetime.date(2011, 01, 01)
    end_date   = datetime.date(2014, 01, 01)
    
    dates_2011_2013 = [ start_date + datetime.timedelta(n) for n in range(int ((end_date - start_date).days))]
    

    All credits to this answer!

    0 讨论(0)
  • 2020-11-22 11:28

    Here's a slightly different answer building off of S.Lott's answer that gives a list of dates between two dates start and end. In the example below, from the start of 2017 to today.

    start = datetime.datetime(2017,1,1)
    end = datetime.datetime.today()
    daterange = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)]
    
    0 讨论(0)
  • 2020-11-22 11:30

    yeah, reinvent the wheel.... just search the forum and you'll get something like this:

    from dateutil import rrule
    from datetime import datetime
    
    list(rrule.rrule(rrule.DAILY,count=100,dtstart=datetime.now()))
    
    0 讨论(0)
  • 2020-11-22 11:30

    If there are two dates and you need the range try

    from dateutil import rrule, parser
    date1 = '1995-01-01'
    date2 = '1995-02-28'
    datesx = list(rrule.rrule(rrule.DAILY, dtstart=parser.parse(date1), until=parser.parse(date2)))
    
    0 讨论(0)
  • 2020-11-22 11:33

    Get range of dates between specified start and end date (Optimized for time & space complexity):

    import datetime
    
    start = datetime.datetime.strptime("21-06-2014", "%d-%m-%Y")
    end = datetime.datetime.strptime("07-07-2014", "%d-%m-%Y")
    date_generated = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)]
    
    for date in date_generated:
        print date.strftime("%d-%m-%Y")
    
    0 讨论(0)
  • 2020-11-22 11:33

    A monthly date range generator with datetime and dateutil. Simple and easy to understand:

    import datetime as dt
    from dateutil.relativedelta import relativedelta
    
    def month_range(start_date, n_months):
            for m in range(n_months):
                yield start_date + relativedelta(months=+m)
    
    0 讨论(0)
提交回复
热议问题