Iterating through a range of dates in Python

后端 未结 23 1341
醉酒成梦
醉酒成梦 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:56

    This function has some extra features:

    • can pass a string matching the DATE_FORMAT for start or end and it is converted to a date object
    • can pass a date object for start or end
    • error checking in case the end is older than the start

      import datetime
      from datetime import timedelta
      
      
      DATE_FORMAT = '%Y/%m/%d'
      
      def daterange(start, end):
            def convert(date):
                  try:
                        date = datetime.datetime.strptime(date, DATE_FORMAT)
                        return date.date()
                  except TypeError:
                        return date
      
            def get_date(n):
                  return datetime.datetime.strftime(convert(start) + timedelta(days=n), DATE_FORMAT)
      
            days = (convert(end) - convert(start)).days
            if days <= 0:
                  raise ValueError('The start date must be before the end date.')
            for n in range(0, days):
                  yield get_date(n)
      
      
      start = '2014/12/1'
      end = '2014/12/31'
      print list(daterange(start, end))
      
      start_ = datetime.date.today()
      end = '2015/12/1'
      print list(daterange(start, end))
      

提交回复
热议问题