【问题标题】:Python - How to exclude Sat. and Sun. from weeksPython - 如何排除周六。和太阳。从几周
【发布时间】:2018-07-20 16:33:53
【问题描述】:

我希望有人能给我一些示例,说明我可以返回执行以下操作的日历数据。


  1. 返回任何给定月份(过去/现在/未来)的天数, 但在排除周六和周日之后。

示例:

input('年份:') — 2018

input('月份:') — 7

最终结果:(2018年)(7月)的工作日数为(22)。


  1. 将迭代器分配给排除周六后的每个工作日。和太阳。

示例:

input('年份:') — 2018

input('月份:') — 7

input('date:') — 20

最终结果: (20) 是 (Frid​​ay) 并且是 (15) 工作日。

这是我目前能够创建的代码...

import calendar

year = float(input('Year: '))
month = float(input('Month: '))
input_year = []
input_month = []

if year >= 1000 and year <=3000:
    input_year.append(year)
if month >= 1 and month <=12:
    input_month.append(month)

cal_format = calendar.TextCalendar(calendar.MONDAY)
result_cal = cal_format.formatmonth(int(input_year[0]), int(input_month[0]))
print(result_cal)

THE END RESULT IS...

Year: 1978
Month: 3
     March 1978
Mo Tu We Th Fr Sa Su
       1  2  3  4  5
 6  7  8  9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31

这只会打印出带有 Sat 的文本日历。和太阳在每个周末,所以我至少可以在视觉上排除它们。但我真的很希望能够以编程方式排除它们,并能够输入上述变量来计算一个月中的工作日,以及该月内每天的哪个工作日。

【问题讨论】:

    标签: python calendar


    【解决方案1】:

    获取一个月的工作日数:

    import calendar
    
    weekdays = 0
    cal = calendar.Calendar()
    
    for week in cal.monthdayscalendar(2018, 7):
        for i, day in enumerate(week):
            # Check if is a weekday and the day is from this month
            if i < 5 and day != 0:
                weekdays += 1
    
    print weekdays
    

    要获取特定日期的工作日数,您可以修改上述代码以在达到输入日期时返回工作日数。

    【讨论】:

      【解决方案2】:

      这里有一种方法可以找到以前的工作日数:

      请注意,年、月、日的类型转换为int

      import calendar
      
      year = int(input('Year: '))
      month = int(input('Month: '))
      day = int(input('Day: '))
      
      full_wks = day / 7
      extra_days = day % 7
      
      first_day = calendar.weekday(year, month, 1)
      if first_day >= 5:              # if month begins on a weekend
          weekend = 7 - first_day     # yields 1 if Sunday, 2 if Saturday
          extra_days -= weekend
      
      weekdays = full_wks * 5 + extra_days
      
      ordinal = lambda n: "{}{}".format(n, 'tsnrhtdd'[n%5*(n%100^15>4>n%10)::4])
      
      print "{}/{} is the {} weekday in the month.".format(month, day, ordinal(weekdays))
      

      输出:

      Year: 2018
      Month: 7
      Day: 20
      7/20 is the 15th weekday in the month.
      

      Code Golf 上的 xsot 的序数转换。

      【讨论】:

        【解决方案3】:

        检查日期的星期几的一种方法是使用date 对象的weekday() 方法。它在python标准库datetime模块中。

        date.weekday()

        以整数形式返回星期几,其中星期一为 0,星期日为 6。例如,date(2002, 12, 4).weekday() == 2,星期三。另见isoweekday()

        import datetime
        
        num_of_weekdays = 0
        weekday_list = []
        
        start_date = datetime.date(int(input_year[0]), int(input_month[0]), 1)
        cur_date = start_date
        while cur_date.month == start_date.month:
            if 0 <= cur_date.weekday() <= 4:  # if it is a weekday
                num_of_weekdays += 1
                weekday_list.append(cur_date.day)
            cur_date += datetime.timedelta(days=1)
        
        print("The number of weekdays in ({}) of ({}) is ({}).".format(
            input_month[0], input_year[0], num_of_weekdays))
        
        date_ = datetime.date(int(input_year[0]), int(input_month[0]), int(input_date[0]))
        index = weekday_list.index(int(input_date[0])) + 1
        print("The ({}) is a ({}) and is the ({}) weekday of ({}), ({}).".format(
            date_.day, date_.strftime('%A'), index, date_.month, date_.year)
        

        【讨论】:

          【解决方案4】:

          我在大约 10 分钟内完成了一个简单的解决方案。我的方法在很大程度上依赖于列表推导和字符串方法,例如 join 和 split,因此如果您不熟悉它们,我建议您查看它们。首先将结果分成几行,标题需要重新定位,其他行需要删除最后一个字符。

          使用strip()方法重新居中第一行,去除行首的空白,然后预先添加两个空格。

          使用列表推导仅包含每行的前 15 个字符,以此度过周末。

          最后一部分是最难的。这个想法是计算我的格式化日历中有多少天数。先把所有有天数的行放在一个大行里,然后用空格分割,得到一个天数的列表,最后使用列表的大小。

          import calendar
          
          year = float(input('Year: '))
          month = float(input('Month: '))
          input_year = []
          input_month = []
          
          if year >= 1000 and year <=3000:
              input_year.append(year)
          if month >= 1 and month <=12:
              input_month.append(month)
          
          cal_format = calendar.TextCalendar(calendar.MONDAY)
          result_cal = cal_format.formatmonth(int(input_year[0]), int(input_month[0]))
          
          lines = result_cal.split("\n") # Split result_cal into a list of lines
          title_line = lines[0] # Save first line, we want to edit this differently
          title_line = "  " + title_line.strip() # Change the indentation of the title line
          
          
          lines = lines[1:] # Now select lines below the first 
          lines = [line[:3*5] for line in lines] # Only Keep first 15 characters or each
                                                 # line to exclude weekends. (5 weekdays *
                                                 # 3 chars per day)
          
          lines = [line for line in lines if len(line.strip())] # Don't include empty lines
                                                                # happens if month starts
                                                                # on a weekend.
          
          # prints out the result
          print(title_line)
          for line in lines:
              print(line)
          
          # Next work out how many working days in month.
          nums = "".join(lines[1:]).split(" ") # Three parts: first lines[1:] means this
                                               # only looks at the portion of the calendar
                                               # with numbers written on then. 2nd "".join()
                                               # joins the lines into a single string on 1 line
                                               # 3rd the .split(" ") splits the string based on spaces
                                               # unfortunatly 2 consecutive spaces result in an empty
                                               # string.
          
          nums = [num for num in nums if len(num)] # Filters the empty string.
          print(f"There are {len(nums)} working days in the month you selected") # Prints result
          #(uses f-string, you may want to look them up, I find them to be very useful)
          

          【讨论】:

            猜你喜欢
            • 2018-09-25
            • 1970-01-01
            • 1970-01-01
            • 2018-06-01
            • 1970-01-01
            • 1970-01-01
            • 2019-09-07
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多