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

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

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

实例

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

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


当前回答

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

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

输出:

4 Friday

其他回答

这是一个新的方法。星期天是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

以下是如何将小端字符串日期列表转换为datetime:

import datetime, time
ls = ['31/1/2007', '14/2/2017']
for d in ls:    
    dt = datetime.datetime.strptime(d, "%d/%m/%Y")
    print(dt)
    print(dt.strftime("%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

intDay = datetime.date(year=2000, month=12, day=1).weekday()
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
print(days[intDay])

输出应为:

Friday

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

or

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