Reputation: 49
def get_next_monday(year, month, day):
date0 = datetime.date(year, month, day)
next_monday = date0 + datetime.timedelta(7 - date0.weekday() or 7)
return next_monday
date2 = datetime.datetime.now().strftime("%Y, %m, %d")
findnextweek = get_next_monday(date2)
If I replace (year, month, day)
with (date2)
I get Integer required. Otherwise, I get a different error
TypeError: get_next_monday() takes exactly 3 arguments (1 given)
Upvotes: 0
Views: 70
Reputation:
You have some little problems in your code. Here's the fix and explanation:
import datetime
def get_next_monday(year, month, day):
# if you want to accept str and int, you must convert the strings
date0 = datetime.date(int(year), int(month), int(day))
next_monday = date0 + datetime.timedelta(7 - date0.weekday() or 7)
return next_monday
# you must convert the date in a list, because `get_next_monday` takes 3 arguments.
initial_date = datetime.datetime.now().strftime("%Y, %m, %d").split(',')
# you must un-pack the date
findnextweek = get_next_monday(*initial_date)
print(findnextweek)
Note that normally you should be calling get_next_monday
with something like get_next_monday(2016, 6, 10)
or get_next_monday('2016', '6', '10')
.
There's no much sense of creating datetime object, converting it in to an string, then a list, and finally re-converting in to a datetime object.
Anyways I hope it help you :)
Upvotes: 2
Reputation: 48006
You are passing a string value to your get_next_monday
function but it is expecting 3 arguments.
date2 = datetime.datetime.now().strftime("%Y, %m, %d")
This will return a string similar to this: '2016, 06, 28'
.
You'll want to split that string into 3 variables in order to pass it to your function.
There are many ways to do this but I'll provide a super simple option:
year, month, day = date2.split(',')
This will populate year
with "2016", month with " 06" and day with " 28". You can then pass these three variables to your get_next_monday
function. Don't forget to convert the arguments to numbers before passing them to the date
function:
datetime.date( int(year), int(month), int(day) )
As you can see, the split function takes a string as an input and "breaks" the string up into parts. It will "break" the string every time it sees a "," character because that is the argument we are passing to the split
function. In our example, the strings will still include some spaces - you could use strip()
to remove them, or you could change the date format to not have spaces: strftime("%Y,%m,%d")
.
Upvotes: 1