I need to get some information about some dates and I don't know what to use. for example: I pass year, month, day (something like 1990, 5, 15) arguments to a module, and the module returns what day of week is the date we passed. I want it in Python 3.
Asked
Active
Viewed 7,064 times
2
-
1Possible duplicate of [How do I get the day of week given a date in Python?](https://stackoverflow.com/questions/9847213/how-do-i-get-the-day-of-week-given-a-date-in-python) – MyNameIsCaleb May 08 '19 at 17:01
4 Answers
2
If you are using a datetime.date
object you can use the weekday()
function. Converting to a date object inside your module should be trivial if you are passing in the day, month and year.
https://docs.python.org/3.7/library/datetime.html#datetime.date.weekday
Numeric representation
Example function:
import datetime
def weekday_from_date(day, month, year):
return datetime.date(day=day, month=month, year=year).weekday()
Example usage:
>>> weekday_from_date(day=1, month=1, year=1995)
6
String representation
Combined with the calendar
module and the day_name
array you can also get it displayed as a string easily.
https://docs.python.org/3.7/library/calendar.html#calendar.day_name
Example function:
import datetime
import calendar
def weekday_from_date(day, month, year):
return calendar.day_name[
datetime.date(day=day, month=month, year=year).weekday()
]
Example usage:
>>> weekday_from_date(day=1, month=1, year=1995)
'Sunday'
Unit Tests
Using pytest
writing a series of super fast unit tests should be straightforward to prove it's correctness. You can add to this suite as you please.
import pytest
@pytest.mark.parametrize(
['day', 'month', 'year', 'expected_weekday'],
[
(1, 1, 1995, 6),
(2, 1, 1995, 0),
(3, 1, 1995, 1),
(6, 6, 1999, 6)
]
)
def test_weekday_from_date(day, month, year, expected_weekday):
assert weekday_from_date(day, month, year) == expected_weekday

Peter Featherstone
- 7,835
- 4
- 32
- 64
0
You could use datetime module
from datetime import datetime
date_string = '1990, 5, 15'
date = datetime.strptime(date_string, "%Y, %m, %d")
date.weekday()
1

martbln
- 314
- 2
- 10