How do I get the day of week given a date in Pytho

2018-12-31 23:42发布

问题:

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 its Friday)

回答1:

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.



回答2:

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


回答3:

Use date.weekday() or date.isoweekday().



回答4:

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


回答5:

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


回答6:

If you\'d like to have the date in English:

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

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



回答7:

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]


回答8:

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:

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:

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


回答11:

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


回答12:

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


回答13:

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)


回答14:

Using Canlendar Module

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


回答15:

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)