在Python中使用if语句:如果datetime.day == WEDNESDAY,则调用wed_module()

-1 投票
2 回答
2955 浏览
提问于 2025-04-18 17:14

好的,我想在Python中为每周的每一天调用一个不同的模块。现在我的代码是这样的:

def today_Shift():
    import time
    import datetime
    import calendar
    print "Day of week:", datetime.date.today().strftime("%A")

#This gives me the day of the week. 
#Now I need to know what to compare to what, to determine if for example the day of the       #week is == wednesday. 
#If the day of the week is == Wednesday Then
# call wed_info
#elif:
# call tues_info
#etc.

2 个回答

1

你可以为每个星期的每一天写一个特定的功能,这个功能可以做任何事情。

def wedFunc():
    print "This is for wednesday"

def friFunc():
    print "This is for friday"

然后你可以创建一个字典,把每一天和对应的功能联系起来。

dayFunctionDict = {"Wednesday" : wedFunc, "Friday" : friFunc}

接着你就可以调用合适的功能:

>>> dayFunctionDict['Wednesday']()
This is for wednesday

使用 datetime 模块。

>>> dayFunctionDict[datetime.date.today().strftime("%A")]()
This is for wednesday
3

你可以使用一个叫做 weekday 的函数。这个函数会返回一周中的某一天,用数字表示,其中星期一是0,星期天是6。

weekday = datetime.datetime.today().weekday()
if weekday == 4:
  #call wen_module

撰写回答