标签归档:weekday

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

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

我想找出以下内容:给定日期(datetime对象),星期几是几号?

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

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

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

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

I want to find out the following: given a date (datetime object), what is the corresponding day of the week?

For instance, Sunday is the first day, Monday: second day.. and so on

And then if the input is something like today’s date.

Example

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

The output is maybe 6 (since it’s Friday)


回答 0

使用weekday()docs):

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

从文档中:

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

Use weekday() (docs):

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

From the documentation:

Return the day of the week as an integer, where Monday is 0 and Sunday is 6.


回答 1

如果您想用英文注明日期:

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

If you’d like to have the date in English:

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

回答 2

如果您想用英文注明日期:

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

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

If you’d like to have the date in English:

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

Read more: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior


回答 3


回答 4

我解决了CodeChef 问题

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

I solved this for a 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"))

回答 5

没有导入日期为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')

A solution whithout imports for dates after 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')

回答 6

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

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

This is a solution if the date is a datetime object.

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

回答 7

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

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

输出:

4 Friday

If you have dates as a string, it might be easier to do it using pandas’ Timestamp

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

Output:

4 Friday

回答 8

datetime库有时会因strptime()提供错误,因此我切换到dateutil库。这是一个如何使用它的示例:

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

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

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

这对我来说很快。使用日期时间库时遇到问题,因为我想存储工作日名称而不是工作日编号,并且使用日期时间库的格式引起了问题。如果您对此没有问题,那就太好了!如果您愿意,您绝对可以这样做,因为它也具有更简单的语法。希望这可以帮助。

datetime library sometimes gives errors with strptime() so I switched to dateutil library. Here’s an example of how you can use it :

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

The output that you get from this is 'Mon'. If you want the output as ‘Monday’, use the following :

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

This worked for me pretty quickly. I was having problems while using the datetime library because I wanted to store the weekday name instead of weekday number and the format from using the datetime library was causing problems. If you’re not having problems with this, great! If you are, you cand efinitely go for this as it has a simpler syntax as well. Hope this helps.


回答 9

假设给定日期,月份和年份,则可以执行以下操作:

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)

Assuming you are given the day, month, and year, you could do:

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

假设您有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)

Say you have timeStamp: String variable, YYYY-MM-DD HH:MM:SS

step 1: convert it to dateTime function with blow code…

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

Step 2 : Now you can extract all the required feature as below which will create new Column for each of the fild- hour,month,day of week,year, date

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)

回答 11

如果您有理由避免使用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

If you have reason to avoid the use of the datetime module, then this function will work.

Note: The change from the Julian to the Gregorian calendar is assumed to have occurred in 1582. If this is not true for your calendar of interest then change the line if year > 1582: accordingly.

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

回答 12

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

If you’re not solely reliant on the datetime module, calendar might be a better alternative. This, for example, will provide you with the day codes:

calendar.weekday(2017,12,22);

And this will give you the day itself:

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

Or in the style of python, as a one liner:

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

回答 13

我们可以帮助熊猫:

import pandas as pd

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

datetime(2017, 10, 20)

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

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

使用weekday()和weekday_name:

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

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

输出将是:

4

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

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

输出将是:

'Friday'

如果在Pandas数据框中具有日期列,则:

现在假设您有一个熊猫数据框,其日期列如下所示: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]

现在,如果我们想知道星期一,星期二,.. etc等工作日的名称,可以使用.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

We can take help of Pandas:

import pandas as pd

As mentioned above in the problem We have:

datetime(2017, 10, 20)

If execute this line in the jupyter notebook we have an output like this:

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

Using weekday() and weekday_name:

If you want weekdays in integer number format then use:

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

The output will be:

4

And if you want it as name of the day like Sunday, Monday, Friday, etc you can use:

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

The output will be:

'Friday'

If having a dates column in Pandas dataframe then:

Now suppose if you have a pandas dataframe having a date column like this: 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]

Now If we want to know the name of the weekday like Monday, Tuesday, ..etc we can use .weekday_name as follows:

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

the output will be:

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

And if we want the integer number of weekday from this Dates column then we can use:

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

The output will look like this:

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

回答 14

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

Output Sample

08 05 2015
Friday

回答 15

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

这应该给您您的真实日期-1 =星期日,2 =星期一,依此类推…

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

this should give you your real day number – 1 = sunday, 2 = monday, etc…


回答 16

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

To get Sunday as 1 through Saturday as 7, this is the simplest solution to your question:

datetime.date.today().toordinal()%7 + 1

All of them:

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

Output:

1 == Sunday
2 == Monday
3 == Tuesday
4 == Wednesday
5 == Thursday
6 == Friday
7 == Saturday

回答 17

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

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)

here is how to convert a listof dates to date

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)

回答 18

使用坎伦达模块

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

Using Canlendar Module

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

回答 19

这是我的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)

Here is my python3 implementation.

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)

回答 20

使用此代码:

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

use this code:

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

回答 21

将numpy导入为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

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