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

2018-12-31 23:40发布

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)

15条回答
骚的不知所云
2楼-- · 2019-01-01 00:43

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")
查看更多
素衣白纱
3楼-- · 2019-01-01 00:45

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

查看更多
皆成旧梦
4楼-- · 2019-01-01 00:46

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
查看更多
登录 后发表回答