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

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

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

实例

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

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


当前回答

如果你想用英语约会:

from datetime import datetime
datetime.today().strftime('%A')
'Wednesday'

阅读更多信息:https://docs.python.org/3/library/datetime.html#strftime-结构时间行为

其他回答

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

一个简单、直接但尚未提及的选项:

import datetime
...
givenDateObj = datetime.date(2017, 10, 20)
weekday      = givenDateObj.isocalendar()[2] # 5
weeknumber   = givenDateObj.isocalendar()[1] # 42
import datetime
int(datetime.datetime.today().strftime('%w'))+1

这应该会给你一个真实的数字-1=星期天,2=星期一,等等。。。

如果你想用英语约会:

from datetime import datetime
datetime.today().strftime('%A')
'Wednesday'

阅读更多信息:https://docs.python.org/3/library/datetime.html#strftime-结构时间行为

import numpy as np

def date(df):
    df['weekday'] = df['date'].dt.day_name()

    conditions = [(df['weekday'] == 'Sunday'),
              (df['weekday'] == 'Monday'),
              (df['weekday'] == 'Tuesday'),
              (df['weekday'] == 'Wednesday'),
              (df['weekday'] == 'Thursday'),
              (df['weekday'] == 'Friday'),
              (df['weekday'] == 'Saturday')]

    choices = [0, 1, 2, 3, 4, 5, 6]

    df['week'] = np.select(conditions, choices)

    return df