Reputation:
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.
Upvotes: 2
Views: 9534
Reputation: 8112
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
Upvotes: 2
Reputation: 8933
You can use weekday()
import datetime
week = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
week[datetime.datetime(1990,5,15).weekday()]
and you get:
'Tuesday'
Upvotes: 0
Reputation: 314
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
Upvotes: 0