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

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

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

实例

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

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


当前回答

datetime库有时会出现strptime()错误,所以我切换到dateutil库。下面是一个如何使用它的示例:

from dateutil import parser
parser.parse('January 11, 2010').strftime("%a")

您从中获得的输出是“Mon”。如果希望输出为“星期一”,请使用以下命令:

parser.parse('January 11, 2010').strftime("%A")

这对我很快奏效。我在使用日期时间库时遇到了问题,因为我想存储工作日名称而不是工作日编号,而使用日期时间的格式导致了问题。如果你对此没有问题,那太好了!如果你是这样的话,你可以明确地这样做,因为它的语法也更简单。希望这有帮助。

其他回答

如果您不完全依赖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)]

如果你想用英语约会:

from datetime import date
import calendar
my_date = date.today()
calendar.day_name[my_date.weekday()]  #'Wednesday'

假设你得到了日期、月份和年份,你可以做到:

import datetime
DayL = ['Mon','Tues','Wednes','Thurs','Fri','Satur','Sun']
date = DayL[datetime.date(year,month,day).weekday()] + 'day'
#Set day, month, year to your value
#Now, date is set as an actual day, not a number from 0 to 6.

print(date)

如果日期是datetime对象,这是一个解决方案。

import datetime
def dow(date):
    days=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
    dayNumber=date.weekday()
    print days[dayNumber]

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