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)
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.
If you'd like to have the date in English:
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:And this will give you the day itself:
Or in the style of python, as a one liner:
datetime library sometimes gives errors with strptime() so I switched to dateutil library. Here's an example of how you can use it :
The output that you get from this is
'Mon'
. If you want the output as 'Monday', use the following :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.
Assuming you are given the day, month, and year, you could do:
Here is my python3 implementation.