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, Mond
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
use this code:
import pandas as pd
from datetime import datetime
print(pd.DatetimeIndex(df['give_date']).day)
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]
A simple, straightforward and still not mentioned option:
import datetime
...
givenDateObj = datetime.date(2017, 10, 20)
weekday = givenDateObj.isocalendar()[2] # 5
weeknumber = givenDateObj.isocalendar()[1] # 42
Use date.weekday() or date.isoweekday().
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