我想了解以下内容:给定一个日期(datetime对象),一周中对应的日期是什么?

例如,星期天是第一天,星期一是第二天。。等等

然后如果输入的内容类似于今天的日期。

实例

>>> today = datetime.datetime(2017, 10, 20)
>>> today.get_weekday()  # what I look for

产量可能是6(因为现在是星期五)


当前回答

使用Canlendar模块

import calendar
a=calendar.weekday(year,month,day)
days=["MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY","SUNDAY"]
print(days[a])

其他回答

要让星期天1点到星期六7点,这是解决问题的最简单方法:

datetime.date.today().toordinal()%7 + 1

所有这些:

import datetime

today = datetime.date.today()
sunday = today - datetime.timedelta(today.weekday()+1)

for i in range(7):
    tmp_date = sunday + datetime.timedelta(i)
    print tmp_date.toordinal()%7 + 1, '==', tmp_date.strftime('%A')

输出:

1 == Sunday
2 == Monday
3 == Tuesday
4 == Wednesday
5 == Thursday
6 == Friday
7 == Saturday

假设你得到了日期、月份和年份,你可以做到:

import datetime
DayL = ['Mon','Tues','Wednes','Thurs','Fri','Satur','Sun']
date = DayL[datetime.date(year,month,day).weekday()] + 'day'
#Set day, month, year to your value
#Now, date is set as an actual day, not a number from 0 to 6.

print(date)

这是我的python3实现。

months = {'jan' : 1, 'feb' : 4, 'mar' : 4, 'apr':0, 'may':2, 'jun':5, 'jul':6, 'aug':3, 'sep':6, 'oct':1, 'nov':4, 'dec':6}
dates = {'Sunday':1, 'Monday':2, 'Tuesday':3, 'Wednesday':4, 'Thursday':5, 'Friday':6, 'Saterday':0}
ranges = {'1800-1899':2, '1900-1999':0, '2000-2099':6, '2100-2199':4, '2200-2299':2}

def getValue(val, dic):
    if(len(val)==4):
        for k,v in dic.items():
            x,y=int(k.split('-')[0]),int(k.split('-')[1])
            val = int(val)
            if(val>=x and val<=y):
                return v
    else:
        return dic[val]

def getDate(val):
    return (list(dates.keys())[list(dates.values()).index(val)]) 



def main(myDate):
    dateArray = myDate.split('-')
    # print(dateArray)
    date,month,year = dateArray[2],dateArray[1],dateArray[0]
    # print(date,month,year)

    date = int(date)
    month_v = getValue(month, months)
    year_2 = int(year[2:])
    div = year_2//4
    year_v = getValue(year, ranges)
    sumAll = date+month_v+year_2+div+year_v
    val = (sumAll)%7
    str_date = getDate(val)

    print('{} is a {}.'.format(myDate, str_date))

if __name__ == "__main__":
    testDate = '2018-mar-4'
    main(testDate)

如果您将日期作为字符串,那么使用panda的时间戳可能更容易

import pandas as pd
df = pd.Timestamp("2019-04-12")
print(df.dayofweek, df.weekday_name)

输出:

4 Friday
import datetime
import calendar

day, month, year = map(int, input().split())
my_date = datetime.date(year, month, day)
print(calendar.day_name[my_date.weekday()])

输出示例

08 05 2015
Friday