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

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

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

实例

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

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


当前回答

当星期一为0,星期日为6时,使用date.weekday()

or

date.isoweekday(),当周一是1,周日是7

其他回答

当星期一为0,星期日为6时,使用date.weekday()

or

date.isoweekday(),当周一是1,周日是7

要让星期天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 pandas as pd
from datetime import datetime
print(pd.DatetimeIndex(df['give_date']).day)

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

import datetime
...
givenDateObj = datetime.date(2017, 10, 20)
weekday      = givenDateObj.isocalendar()[2] # 5
weeknumber   = givenDateObj.isocalendar()[1] # 42
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