如何获得给定日期的星期几?

我想知道以下内容:给定一个日期(datetime对象),一周中对应的是哪一天?

例如,星期日是第一天,星期一:第二天…等等

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

示例

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

输出可能是6(因为是星期五)

1225581 次浏览

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

date.isoweekday()当星期一是1,星期天是7

使用weekday()

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

留档

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

我为CodeChef问题解决了这个问题。

import datetimedt = '21/03/2012'day, month, year = (int(x) for x in dt.split('/'))ans = datetime.date(year, month, day)print (ans.strftime("%A"))

1700/1/1之后的日期不导入的解决方案

def weekDay(year, month, day):offset = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]week   = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']afterFeb = 1if month > 2: afterFeb = 0aux = year - 1700 - afterFeb# dayOfWeek for 1700/1/1 = 5, FridaydayOfWeek  = 5# partial sum of days betweem current date and 1700/1/1dayOfWeek += (aux + afterFeb) * 365# leap year correctiondayOfWeek += aux / 4 - aux / 100 + (aux + 100) / 400# sum monthly and day offsetsdayOfWeek += offset[month - 1] + (day - 1)dayOfWeek %= 7return dayOfWeek, week[dayOfWeek]
print weekDay(2013, 6, 15) == (6, 'Saturday')print weekDay(1969, 7, 20) == (0, 'Sunday')print weekDay(1945, 4, 30) == (1, 'Monday')print weekDay(1900, 1, 1)  == (1, 'Monday')print weekDay(1789, 7, 14) == (2, 'Tuesday')

假设你有日、月和年,你可以这样做:

import datetimeDayL = ['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)

将周日作为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 == Sunday2 == Monday3 == Tuesday4 == Wednesday5 == Thursday6 == Friday7 == Saturday

如果您想要英文日期:

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

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

注意:从儒略历到公历的更改被假定为发生在1582年。如果您感兴趣的日历不是这样,请相应地更改第0行。

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

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

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

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

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

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

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

这对我来说很快就奏效了。我在使用datetime库时遇到了问题,因为我想存储工作日名称而不是工作日数字,并且使用datetime库的格式导致了问题。如果你对此没有问题,太好了!如果你是,你可以无限地去做这个,因为它也有更简单的语法。希望这有帮助。

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

import datetime, timels = ['31/1/2007', '14/2/2017']for d in ls:dt = datetime.datetime.strptime(d, "%d/%m/%Y")print(dt)print(dt.strftime("%A"))

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

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)]

使用Canlender模块

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

这是我的python3实现。

months = {'jan' : 1, 'feb' : 4, 'mar' : 4, 'apr':0, 'may':2, 'jun':5, 'jul':6, 'aug':3, 'sep':6, 'oct':1, 'nov':4, 'dec':6}dates = {'Sunday':1, 'Monday':2, 'Tuesday':3, 'Wednesday':4, 'Thursday':5, 'Friday':6, 'Saterday':0}ranges = {'1800-1899':2, '1900-1999':0, '2000-2099':6, '2100-2199':4, '2200-2299':2}
def getValue(val, dic):if(len(val)==4):for k,v in dic.items():x,y=int(k.split('-')[0]),int(k.split('-')[1])val = int(val)if(val>=x and val<=y):return velse:return dic[val]
def getDate(val):return (list(dates.keys())[list(dates.values()).index(val)])


def main(myDate):dateArray = myDate.split('-')# print(dateArray)date,month,year = dateArray[2],dateArray[1],dateArray[0]# print(date,month,year)
date = int(date)month_v = getValue(month, months)year_2 = int(year[2:])div = year_2//4year_v = getValue(year, ranges)sumAll = date+month_v+year_2+div+year_vval = (sumAll)%7str_date = getDate(val)
print('{} is a {}.'.format(myDate, str_date))
if __name__ == "__main__":testDate = '2018-mar-4'main(testDate)

如果您想要英文日期:

from datetime import datetimedatetime.today().strftime('%A')'Wednesday'

阅读更多:https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

我们可以帮助Pandas:

import pandas as pd

如上所述的问题我们有:

datetime(2017, 10, 20)

如果在jupyter笔记本中执行这一行,我们会得到这样的输出:

datetime.datetime(2017, 10, 20, 0, 0)

使用平日()和weekday_name:

如果您想要整数格式的工作日,请使用:

pd.to_datetime(datetime(2017, 10, 20)).weekday()

输出将是:

4

如果你想把它作为周日、周一、周五等日子的名称,你可以使用:

pd.to_datetime(datetime(2017, 10, 20)).weekday_name

输出将是:

'Friday'

如果在Pandas dataframe中有一个日期列,那么:

现在假设你有一个熊猫数据框,它的日期列是这样的:pd示例数据帧['Dates']. head(5)

0   2010-04-011   2010-04-022   2010-04-033   2010-04-044   2010-04-05Name: Dates, dtype: datetime64[ns]

现在,如果我们想知道工作日的名称,如星期一,星期二等,我们可以使用.weekday_name如下:

pdExampleDataFrame.head(5)['Dates'].dt.weekday_name

输出将是:

0    Thursday1      Friday2    Saturday3      Sunday4      MondayName: Dates, dtype: object

如果我们想要这个日期列中的工作日的整数,那么我们可以使用:

pdExampleDataFrame.head(5)['Dates'].apply(lambda x: x.weekday())

输出将如下所示:

0    31    42    53    64    0Name: Dates, dtype: int64
import datetimeimport calendar
day, month, year = map(int, input().split())my_date = datetime.date(year, month, day)print(calendar.day_name[my_date.weekday()])

输出样本

08 05 2015Friday

说你有timeStamp:字符串变量,YYYY-MM-DD HH: MM: SS

步骤1:将其转换为带有打击代码的dateTime函数…

df['timeStamp'] = pd.to_datetime(df['timeStamp'])

步骤2:现在您可以提取所有必需的功能,如下所示,这将为每个文件创建新列-小时,月,星期几,年,日期

df['Hour'] = df['timeStamp'].apply(lambda time: time.hour)df['Month'] = df['timeStamp'].apply(lambda time: time.month)df['Day of Week'] = df['timeStamp'].apply(lambda time: time.dayofweek)df['Year'] = df['timeStamp'].apply(lambda t: t.year)df['Date'] = df['timeStamp'].apply(lambda t: t.day)

如果你把日期作为一个字符串,那么使用熊猫的时间戳可能会更容易

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

输出:

4 Friday
import datetimeint(datetime.datetime.today().strftime('%w'))+1

这应该给你真正的天数-1=星期日,2=星期一,等等…

使用此代码:

import pandas as pdfrom datetime import datetimeprint(pd.DatetimeIndex(df['give_date']).day)
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

以下是以DD-MM-YYYY格式输入日期的代码,您可以通过更改'%d-%m-%Y'的顺序以及更改分隔符来更改输入格式。

import datetimetry:date = input()date_time_obj = datetime.datetime.strptime(date, '%d-%m-%Y')print(date_time_obj.strftime('%A'))except ValueError:print("Invalid date.")

如果您想生成一个包含日期范围(Date)的列并生成一个转到第一个并分配周日(Week Day)的列,请执行以下操作(我将使用从2008-01-012020-02-01的日期):

import pandas as pddr = pd.date_range(start='2008-01-01', end='2020-02-1')df = pd.DataFrame()df['Date'] = drdf['Week Day'] = pd.to_datetime(dr).weekday

输出如下:

输入图片描述

Week Day从0到6变化,其中0对应周一,6对应周日。

这里有一个简单的代码片段来解决这个问题

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

输出应该是:

Friday

一个简单,直接,仍然没有提到的选项:

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

这不需要星期几的评论。
我推荐这个代码~!

import datetime

DAY_OF_WEEK = {"MONDAY": 0,"TUESDAY": 1,"WEDNESDAY": 2,"THURSDAY": 3,"FRIDAY": 4,"SATURDAY": 5,"SUNDAY": 6}
def string_to_date(dt, format='%Y%m%d'):return datetime.datetime.strptime(dt, format)
def date_to_string(date, format='%Y%m%d'):return datetime.datetime.strftime(date, format)
def day_of_week(dt):return string_to_date(dt).weekday()

dt = '20210101'if day_of_week(dt) == DAY_OF_WEEK['SUNDAY']:None

如果你是中国用户,你可以使用这个包:https://github.com/LKI/chinese-calendar

import datetime
# 判断 2018年4月30号 是不是节假日from chinese_calendar import is_holiday, is_workdayapril_last = datetime.date(2018, 4, 30)assert is_workday(april_last) is Falseassert is_holiday(april_last) is True
# 或者在判断的同时,获取节日名import chinese_calendar as calendar  # 也可以这样 importon_holiday, holiday_name = calendar.get_holiday_detail(april_last)assert on_holiday is Trueassert holiday_name == calendar.Holiday.labour_day.value
# 还能判断法定节假日是不是调休import chinese_calendarassert chinese_calendar.is_in_lieu(datetime.date(2006, 2, 1)) is Falseassert chinese_calendar.is_in_lieu(datetime.date(2006, 2, 2)) is True

这里有个新鲜的方法。星期天是0。

from datetime import datetimetoday = datetime(year=2022, month=6, day=17)print(today.toordinal()%7)  # 5yesterday = datetime(year=1, month=1, day=1)print(today.toordinal()%7)  # 1

在MATLAB中,高斯方法

day_name={'Sun','Mon','Tue','Wed','Thu','Fri','Sat'}month_offset=[0 3 3 6 1 4 6 2 5 0 3 5];  % common year
% input datey1=2022m1=11d1=22
% is y1 leapif mod(y1,4)==0 && mod(y1,100)==0 && mod(y1,400)==0month_offset=[0 3 4 0 2 5 0 3 6 1 4 6];  % offset for leap yearend
% Gregorian calendarweekday_gregor=rem( d1+month_offset(m1) + 5*rem(y1-1,4) +  4*rem(y1-1,100) + 6*rem(y1-1,400),7)
day_name{weekday_gregor+1}

0:星期日1:星期一…6:星期六