【问题标题】:How to get the Nth occurrence of a day of the week for a given month?如何获得给定月份一周中某天的第 N 次出现?
【发布时间】:2016-05-28 20:48:32
【问题描述】:

每月的星期没有定义这个值。 在大多数情况下,开始周和开始月份之间的转换会导致问题。

是否有任何 python 库或算法来计算这个值?

【问题讨论】:

    标签: python python-2.7 date


    【解决方案1】:

    您可以通过循环一个月中的几天并计算您是否遇到第 n 个工作日来计算:

    import datetime
    
    def get_n_weekday(year, month, day_of_week, n):
        count = 0
        for i in xrange(1, 32):
            try:
                d = datetime.date(year, month, i)
            except ValueError:
                break
            if d.isoweekday() == day_of_week:
                count += 1
            if count == n:
                return d
        return None
    

    例如:get_n_weekday(2016, 1, 1, 1) = 2016 年 1 月的第一个星期一,即 datetime.date(2016, 1, 4)

    这使用date.isoweekday(),表示星期一是 1,星期日是 7。

    【讨论】:

      【解决方案2】:

      比 Simeon 的答案更简单的两个解决方案:

      def f1(day_of_month):
          ret = None    
          if ( day_of_month % 7 == 0 ):
              ret = day_of_month/7
          else:
              ret = (day_of_month//7) + 1
          return ret       
      
      
      def f2(day_of_month):
          actual_day = day_of_month
          counter = 0
          while actual_day > 0:
              actual_day = actual_day - 7
              counter = counter + 1
          return counter
      

      【讨论】:

        猜你喜欢
        • 2023-03-30
        • 2013-01-16
        • 2011-03-20
        • 2020-12-08
        • 2012-12-12
        • 2011-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多