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

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

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

实例

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

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


当前回答

如果您是中国用户,您可以使用此软件包:https://github.com/LKI/chinese-calendar

import datetime

# 判断 2018年4月30号 是不是节假日
from chinese_calendar import is_holiday, is_workday
april_last = datetime.date(2018, 4, 30)
assert is_workday(april_last) is False
assert is_holiday(april_last) is True

# 或者在判断的同时,获取节日名
import chinese_calendar as calendar  # 也可以这样 import
on_holiday, holiday_name = calendar.get_holiday_detail(april_last)
assert on_holiday is True
assert holiday_name == calendar.Holiday.labour_day.value

# 还能判断法定节假日是不是调休
import chinese_calendar
assert chinese_calendar.is_in_lieu(datetime.date(2006, 2, 1)) is False
assert chinese_calendar.is_in_lieu(datetime.date(2006, 2, 2)) is True

其他回答

使用weekday():

>>> import datetime
>>> datetime.datetime.today()
datetime.datetime(2012, 3, 23, 23, 24, 55, 173504)
>>> datetime.datetime.today().weekday()
4

根据文档:

以整数形式返回星期几,其中星期一为0,星期日为6。

使用Canlendar模块

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

这是一个新的方法。星期天是0。

from datetime import datetime
today = datetime(year=2022, month=6, day=17)
print(today.toordinal()%7)  # 5
yesterday = datetime(year=1, month=1, day=1)
print(today.toordinal()%7)  # 1
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

使用以下代码:

import pandas as pd
from datetime import datetime
print(pd.DatetimeIndex(df['give_date']).day)