在 Python 中遍历一系列日期 [英] Iterating through a range of dates in Python

查看:53
本文介绍了在 Python 中遍历一系列日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码可以做到这一点,但我怎样才能做得更好?现在我认为它比嵌套循环更好,但是当您在列表理解中使用生成器时,它开始变得像 Perl 一样.

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 generator in a list comprehension.

day_count = (end_date - start_date).days + 1
for single_date in [d for d in (start_date + timedelta(n) for n in range(day_count)) if d <= end_date]:
    print strftime("%Y-%m-%d", single_date.timetuple())

注意事项

  • 我实际上并没有用它来打印.这仅用于演示目的.
  • start_dateend_date 变量是 datetime.date 对象,因为我不需要时间戳.(它们将用于生成报告).
  • Notes

    • I'm not actually using this to print. That's just for demo purposes.
    • The start_date and end_date variables are datetime.date objects because I don't need the timestamps. (They're going to be used to generate a report).
    • 对于 2009-05-30 的开始日期和 2009-06-09 的结束日期:

      For a start date of 2009-05-30 and an end date of 2009-06-09:

      2009-05-30
      2009-05-31
      2009-06-01
      2009-06-02
      2009-06-03
      2009-06-04
      2009-06-05
      2009-06-06
      2009-06-07
      2009-06-08
      2009-06-09
      

      推荐答案

      为什么会有两个嵌套迭代?对我来说,它只用一次迭代生成相同的数据列表:

      Why are there two nested iterations? For me it produces the same list of data with only one iteration:

      for single_date in (start_date + timedelta(n) for n in range(day_count)):
          print ...
      

      并且没有列表被存储,只有一个生成器被迭代.还有如果"在生成器中似乎是不必要的.

      And no list gets stored, only one generator is iterated over. Also the "if" in the generator seems to be unnecessary.

      毕竟,一个线性序列应该只需要一个迭代器,而不是两个.

      After all, a linear sequence should only require one iterator, not two.

      也许最优雅的解决方案是使用生成器函数来完全隐藏/抽象日期范围内的迭代:

      Maybe the most elegant solution is using a generator function to completely hide/abstract the iteration over the range of dates:

      from datetime import date, timedelta
      
      def daterange(start_date, end_date):
          for n in range(int((end_date - start_date).days)):
              yield start_date + timedelta(n)
      
      start_date = date(2013, 1, 1)
      end_date = date(2015, 6, 2)
      for single_date in daterange(start_date, end_date):
          print(single_date.strftime("%Y-%m-%d"))
      

      注意:为了与内置的range() 函数保持一致,此迭代在之前 到达end_date 停止.因此,对于包含迭代的第二天使用,就像使用 range() 一样.

      NB: For consistency with the built-in range() function this iteration stops before reaching the end_date. So for inclusive iteration use the next day, as you would with range().

      这篇关于在 Python 中遍历一系列日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆