Creating a range of dates in Python

后端 未结 20 2116
栀梦
栀梦 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:40
    import datetime    
    def date_generator():
        cur = base = datetime.date.today()
        end  = base + datetime.timedelta(days=100)
        delta = datetime.timedelta(days=1)
        while(end>base):
            base = base+delta
            print base
    
    date_generator()
    
    0 讨论(0)
  • 2020-11-22 11:41
    from datetime import datetime, timedelta
    from dateutil import parser
    def getDateRange(begin, end):
        """  """
        beginDate = parser.parse(begin)
        endDate =  parser.parse(end)
        delta = endDate-beginDate
        numdays = delta.days + 1
        dayList = [datetime.strftime(beginDate + timedelta(days=x), '%Y%m%d') for x in range(0, numdays)]
        return dayList
    
    0 讨论(0)
  • 2020-11-22 11:43

    From above answers i created this example for date generator

    import datetime
    date = datetime.datetime.now()
    time = date.time()
    def date_generator(date, delta):
      counter =0
      date = date - datetime.timedelta(days=delta)
      while counter <= delta:
        yield date
        date = date + datetime.timedelta(days=1)
        counter +=1
    
    for date in date_generator(date, 30):
       if date.date() != datetime.datetime.now().date():
         start_date = datetime.datetime.combine(date, datetime.time())
         end_date = datetime.datetime.combine(date, datetime.time.max)
       else:
         start_date = datetime.datetime.combine(date, datetime.time())
         end_date = datetime.datetime.combine(date, time)
       print('start_date---->',start_date,'end_date---->',end_date)
    
    0 讨论(0)
  • 2020-11-22 11:45

    Another example that counts forwards or backwards, starting from Sandeep's answer.

    from datetime import date, datetime, timedelta
    from typing import Sequence
    def range_of_dates(start_of_range: date, end_of_range: date) -> Sequence[date]:
    
        if start_of_range <= end_of_range:
            return [
                start_of_range + timedelta(days=x)
                for x in range(0, (end_of_range - start_of_range).days + 1)
            ]
        return [
            start_of_range - timedelta(days=x)
            for x in range(0, (start_of_range - end_of_range).days + 1)
        ]
    
    start_of_range = datetime.today().date()
    end_of_range = start_of_range + timedelta(days=3)
    date_range = range_of_dates(start_of_range, end_of_range)
    print(date_range)
    

    gives

    [datetime.date(2019, 12, 20), datetime.date(2019, 12, 21), datetime.date(2019, 12, 22), datetime.date(2019, 12, 23)]
    

    and

    start_of_range = datetime.today().date()
    end_of_range = start_of_range - timedelta(days=3)
    date_range = range_of_dates(start_of_range, end_of_range)
    print(date_range)
    

    gives

    [datetime.date(2019, 12, 20), datetime.date(2019, 12, 19), datetime.date(2019, 12, 18), datetime.date(2019, 12, 17)]
    

    Note that the start date is included in the return, so if you want four total dates, use timedelta(days=3)

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

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

    For example pd.date_range():

    import pandas as pd
    from datetime import datetime
    
    datelist = pd.date_range(datetime.today(), periods=100).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 date range documentation

    In addition it fully supports pytz timezones and can smoothly span spring/autumn DST shifts.

    EDIT by OP:

    If you need actual python datetimes, as opposed to Pandas timestamps:

    import pandas as pd
    from datetime import datetime
    
    pd.date_range(end = datetime.today(), periods = 100).to_pydatetime().tolist()
    
    #OR
    
    pd.date_range(start="2018-09-09",end="2020-02-02")
    
    

    This uses the "end" parameter to match the original question, but if you want descending dates:

    pd.date_range(datetime.today(), periods=100).to_pydatetime().tolist()
    
    0 讨论(0)
  • 2020-11-22 11:50

    Here's a one liner for bash scripts to get a list of weekdays, this is python 3. Easily modified for whatever, the int at the end is the number of days in the past you want.

    python -c "import sys,datetime; print('\n'.join([(datetime.datetime.today() - datetime.timedelta(days=x)).strftime(\"%Y/%m/%d\") for x in range(0,int(sys.argv[1])) if (datetime.datetime.today() - datetime.timedelta(days=x)).isoweekday()<6]))" 10
    

    Here is a variant to provide a start (or rather, end) date

    python -c "import sys,datetime; print('\n'.join([(datetime.datetime.strptime(sys.argv[1],\"%Y/%m/%d\") - datetime.timedelta(days=x)).strftime(\"%Y/%m/%d \") for x in range(0,int(sys.argv[2])) if (datetime.datetime.today() - datetime.timedelta(days=x)).isoweekday()<6]))" 2015/12/30 10
    

    Here is a variant for arbitrary start and end dates. not that this isn't terribly efficient, but is good for putting in a for loop in a bash script:

    python -c "import sys,datetime; print('\n'.join([(datetime.datetime.strptime(sys.argv[1],\"%Y/%m/%d\") + datetime.timedelta(days=x)).strftime(\"%Y/%m/%d\") for x in range(0,int((datetime.datetime.strptime(sys.argv[2], \"%Y/%m/%d\") - datetime.datetime.strptime(sys.argv[1], \"%Y/%m/%d\")).days)) if (datetime.datetime.strptime(sys.argv[1], \"%Y/%m/%d\") + datetime.timedelta(days=x)).isoweekday()<6]))" 2015/12/15 2015/12/30
    
    0 讨论(0)
提交回复
热议问题