我需要编写一个函数来打印给定月份的一周,参数包括周数、开始日期和月份天数(Python)

2024-04-25 09:24:09 发布

您现在位置:Python中文网/ 问答频道 /正文

给定周数,(1,2,…),月1日的日期(1表示星期一,2表示星期二,…),以及月内的天数:返回一个字符串,该字符串由该周内每天的月日组成,从星期一开始,到星期天结束。周数表示月份中的周数

我已完成以下功能: 下面是我的这些函数代码

import datetime
from datetime import datetime
import calendar
from datetime import date

def week(week_num, start_day, days_in_month):
    week_string = ""

    if week_num == 1:
        if start_day == 1:
            week_string = "1 2 3 4 5 6 7"
        elif start_day == 2: 
            week_string = "  1 2 3 4 5 6"
        elif start_day == 3:
            week_string = "    1 2 3 4 5"
        elif start_day == 4:
            week_string = "      1 2 3 4"
        elif start_day == 5:
            week_string = "        1 2 3"
        elif start_day == 6:
            week_string = "          1 2"
        elif start_day == 7:
            week_string = "            1"

    elif week_num == 2:
        if start_day == 1:
            week_string = "8 9 10 11 12 13 14"
        elif start_day == 2: 
            week_string = "7 8 9 10 11 12 13"
        elif start_day == 3:
            week_string = "6 7 8 9 10 11 12"
        elif start_day == 4:
        #carry on in the above way, but this doesn't seem efficient

    return week_string

def main():
    month_name = input("Enter month:\n")
    year = eval(input("Enter year:\n"))


if __name__=='__main__':
    main()

有人对如何做这个功能有什么想法吗?我需要返回一个字符串值

我还有一个想法:

def week(week_num, start_day, days_in_month):
    week_string = ""
    if week_num == 1:
        week_string = ""
        day = start_day

        for i in range(1, 8 -start_day+1):
            week_string = week_string + str(i) + " "
        week_string = "{0:<20}".format(week_string)
    return week_string

此函数的输入和输出示例:

week(1, 3, 30)

返回字符串

' 1 2 3 4 5'
week(2, 3, 30)

返回字符串

' 6 7 8 9 10 11 12’

Tags: 字符串inimportdatetimestringifmaindef
1条回答
网友
1楼 · 发布于 2024-04-25 09:24:09

编辑:你的问题改动很大,一旦我了解你需要什么,我会更新我的回答

datetimecalendar模块应该为您提供所需的一切

from datetime import datetime
import calendar

# is leapyear
calendar.isleap(2020) # True

# just add +1 if you need it in the format that you want
datetime.strptime('25.2.2020', '%d.%m.%Y').weekday() # = 1 = Tuesday

# from name to month number
datetime.strptime('february', '%B').month # = 2

# days in month and weekday of starting month
# with the starting weekday you can easily calculate the number of weeks
calendar.monthrange(2020,2) # = (5, 29), 5=saturday, 29 days in month

对代码的一些一般性注释:

  1. 您可以使用'January'.upper()将其转换为'JANUARY',只需检查month_name=='JANUARY'并保存冗余比较
  2. 您可以使用if month_num in [1,3,5,7,8,10,12]:使其更具可读性

相关问题 更多 >