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

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

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

实例

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

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


当前回答

如果您不完全依赖datetime模块,日历可能是更好的选择。例如,这将为您提供日期代码:

calendar.weekday(2017,12,22);

这将给你一天:

days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
days[calendar.weekday(2017,12,22)]

或者以python的风格,作为一行:

["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"][calendar.weekday(2017,12,22)]

其他回答

如果您有理由避免使用datetime模块,那么此函数将起作用。

注:从儒略历到公历的变化被认为发生在1582年。如果您感兴趣的日历并非如此,那么如果年份>1582,则相应地更改行。

def dow(year,month,day):
    """ day of week, Sunday = 1, Saturday = 7
     http://en.wikipedia.org/wiki/Zeller%27s_congruence """
    m, q = month, day
    if m == 1:
        m = 13
        year -= 1
    elif m == 2:
        m = 14
        year -= 1
    K = year % 100    
    J = year // 100
    f = (q + int(13*(m + 1)/5.0) + K + int(K/4.0))
    fg = f + int(J/4.0) - 2 * J
    fj = f + 5 - J
    if year > 1582:
        h = fg % 7
    else:
        h = fj % 7
    if h == 0:
        h = 7
    return h

如果您是中国用户,您可以使用此软件包: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

以下是如何将小端字符串日期列表转换为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"))

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

or

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

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

import datetime
...
givenDateObj = datetime.date(2017, 10, 20)
weekday      = givenDateObj.isocalendar()[2] # 5
weeknumber   = givenDateObj.isocalendar()[1] # 42