如何在Python中获取日期的星期几?

时间:2012-03-23 22:21:19

标签: python datetime weekday

我想找出以下内容: 给定一个日期(datetime对象),一周的相应日期是什么。

例如星期日是第一天,星期一:第二天......依此类推

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

实施例

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

输出可能是6(自星期五起)

27 个答案:

答案 0 :(得分:718)

使用weekday()docs):

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

来自文档:

  

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

答案 1 :(得分:230)

如果您希望以英文显示日期:

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

答案 2 :(得分:40)

答案 3 :(得分:21)

我为codechef question解决了这个问题。

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

答案 4 :(得分:20)

在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 = 1
    if month > 2: afterFeb = 0
    aux = year - 1700 - afterFeb
    # dayOfWeek for 1700/1/1 = 5, Friday
    dayOfWeek  = 5
    # partial sum of days betweem current date and 1700/1/1
    dayOfWeek += (aux + afterFeb) * 365                  
    # leap year correction    
    dayOfWeek += aux / 4 - aux / 100 + (aux + 100) / 400     
    # sum monthly and day offsets
    dayOfWeek += offset[month - 1] + (day - 1)               
    dayOfWeek %= 7
    return 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')

答案 5 :(得分:20)

如果您想用英文写日期:

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

了解更多: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

答案 6 :(得分:10)

如果日期是日期时间对象,则此解决方案。

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

答案 7 :(得分:9)

这是解决此问题的简单代码段

import datetime

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

输出应为:

Friday

答案 8 :(得分:8)

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

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

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

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

这很快就适合我。我在使用日期时间库时遇到问题,因为我想存储工作日名称而不是工作日编号,而使用日期时间库的格式导致了问题。如果你没有遇到这个问题,太好了!如果你是,那么你可以无限期地使用它,因为它也有更简单的语法。希望这会有所帮助。

答案 9 :(得分:6)

假设您获得了日,月和年,您可以这样做:

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)

答案 10 :(得分:4)

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

注意:假设从Julian到公历的变化发生在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

答案 11 :(得分:4)

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

答案 12 :(得分:3)

说您有 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)

答案 13 :(得分:3)

import datetime
import calendar

day, month, year = map(int, input().split())
my_date = datetime.date(year, month, day)
print(calendar.day_name[my_date.weekday()])

输出样本

08 05 2015
Friday

答案 14 :(得分:2)

如果要生成一列具有日期范围(Date)的列,并生成到第一个列并分配工作日(Week Day)的列,请执行以下操作(I将使用从2008-01-012020-02-01的日期):

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

输出如下:

enter image description here

Week Day的范围是0到6,其中0对应于星期一,而6则对应于星期日。

答案 15 :(得分:2)

我们可以帮助熊猫:

import pandas as pd

如上所述,在问题中,我们有:

datetime(2017, 10, 20)

如果在jupyter笔记本中执行此行,我们将得到如下输出:

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

使用平日()和平日名称:

如果您希望工作日为整数格式,请使用:

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

输出将是:

4

如果您希望将其用作星期天,星期一,星期五等日期的名称,则可以使用:

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

输出将是:

'Friday'

如果熊猫数据框中包含日期列,则:

现在假设您的熊猫数据框的日期列如下所示: pdExampleDataFrame ['Dates']。head(5)

0   2010-04-01
1   2010-04-02
2   2010-04-03
3   2010-04-04
4   2010-04-05
Name: Dates, dtype: datetime64[ns]

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

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

输出将是:

0    Thursday
1      Friday
2    Saturday
3      Sunday
4      Monday
Name: Dates, dtype: object

如果我们想从“日期”列中获取工作日的整数,则可以使用:

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

输出将如下所示:

0    3
1    4
2    5
3    6
4    0
Name: Dates, dtype: int64

答案 16 :(得分:2)

这里是如何将日期列表转换为日期

import datetime,time
ls={'1/1/2007','1/2/2017'}
dt=datetime.datetime.strptime(ls[1], "%m/%d/%Y")
print(dt)
print(dt.month)
print(dt.year)

答案 17 :(得分:2)

要将星期日作为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

答案 18 :(得分:1)

一个简单,直接但仍未提及的选项:

DataFrame

答案 19 :(得分:1)

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

import datetime


DAY_OF_WEEK = {
    "MONDAY": 0,
    "TUESDAY": 1,
    "WEDNESDAY": 2,
    "THURSDAY": 2,
    "FRIDAY": 2,
    "SATURDAY": 2,
    "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

答案 20 :(得分:1)

如果将日期作为字符串,则使用熊猫的时间戳记可能更容易

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

输出:

4 Friday

答案 21 :(得分:1)

这是我的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 v
    else:
        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//4
    year_v = getValue(year, ranges)
    sumAll = date+month_v+year_2+div+year_v
    val = (sumAll)%7
    str_date = getDate(val)

    print('{} is a {}.'.format(myDate, str_date))

if __name__ == "__main__":
    testDate = '2018-mar-4'
    main(testDate)

答案 22 :(得分:1)

使用Canlendar模块

template <int T>
void foo() {
   for constexpr (auto i = 0; i < T; ++i) cout << i << endl;
}

答案 23 :(得分:0)

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

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

答案 24 :(得分:0)

import datetime
int(datetime.datetime.today().strftime('%w'))+1

这应该给您您的真实日期-1 =星期日,2 =星期一,等等...

答案 25 :(得分:-1)

使用此代码:

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

答案 26 :(得分:-1)

将numpy导入为np

定义日期(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