📜  Python程序查找给定日期的星期几

📅  最后修改于: 2022-05-13 01:54:30.367000             🧑  作者: Mango

Python程序查找给定日期的星期几

编写一个Python程序来查找过去或未来任何特定日期的星期几。让输入的格式为“dd mm yyyy”。
例子:

Input : 03 02 1997 
Output : Monday

Input : 31 01 2019
Output : Thursday

已经讨论过的为给定日期查找星期几的方法是 Naive 方法。现在,让我们讨论一下pythonic方法。
方法#1:使用 datetime 模块提供的 weekday() 。
datetime 模块中 date 类的 weekday()函数,返回一个与星期几对应的整数。

Python3
# Python program to Find day of
# the week for a given date
import datetime
import calendar
 
def findDay(date):
    born = datetime.datetime.strptime(date, '%d %m %Y').weekday()
    return (calendar.day_name[born])
 
# Driver program
date = '03 02 2019'
print(findDay(date))


Python3
# Python program to Find day of
# the week for a given date
import datetime
from datetime import date
import calendar
 
def findDay(date):
    day, month, year = (int(i) for i in date.split(' '))   
    born = datetime.date(year, month, day)
    return born.strftime("%A")
 
# Driver program
date = '03 02 2019'
print(findDay(date))


Python3
# Python program to Find day of
# the week for a given date
import calendar
 
def findDay(date):
    day, month, year = (int(i) for i in date.split(' '))   
    dayNumber = calendar.weekday(year, month, day)
    days =["Monday", "Tuesday", "Wednesday", "Thursday",
                         "Friday", "Saturday", "Sunday"]
    return (days[dayNumber])
 
# Driver program
date = '03 02 2019'
print(findDay(date))


输出:
Sunday


方法 #2:使用 strftime() 方法
strftime() 方法将一个或多个格式代码作为参数,并返回一个基于它的格式化字符串。在这里,我们将在提供给定日期的完整工作日名称的方法中传递指令“%A”。

Python3

# Python program to Find day of
# the week for a given date
import datetime
from datetime import date
import calendar
 
def findDay(date):
    day, month, year = (int(i) for i in date.split(' '))   
    born = datetime.date(year, month, day)
    return born.strftime("%A")
 
# Driver program
date = '03 02 2019'
print(findDay(date))
输出:
Sunday


方法#3:通过查找天数
在这种方法中,我们使用日历模块找到天数,然后找到相应的工作日。

Python3

# Python program to Find day of
# the week for a given date
import calendar
 
def findDay(date):
    day, month, year = (int(i) for i in date.split(' '))   
    dayNumber = calendar.weekday(year, month, day)
    days =["Monday", "Tuesday", "Wednesday", "Thursday",
                         "Friday", "Saturday", "Sunday"]
    return (days[dayNumber])
 
# Driver program
date = '03 02 2019'
print(findDay(date))
输出:
Sunday