1cm69 1cm69 - 4 days ago 6
Python Question

Error when using variable in Python calendar.monthrange

I am trying to print the number of days in a month using the Python


I have a script that runs via cron on the 1st of every month and need to return the number of days from the previous month.
I also use the arrow module to better handle and format any date/time calls that I use throughout my scripts.

Because I need to find the number of days in the previous month, which is only back one day from the date the script is being run I just subtract 1 one via timedelta.

Here is a very reduced version of my code but this is the working part:

import calendar
import arrow
import time
from datetime import date, timedelta

yesterday = date.today() - timedelta(1)

cYfDate = yesterday.strftime('%Y.%m.%d')
cYfDateY = arrow.get(cYfDate).format('YYYY')
cYfDateM = arrow.get(cYfDate).format('M')

print cYfDateY
print cYfDateM

print calendar.monthrange(cYfDateY + ',' + cYfDateM)[1]

The first two print lines work perfectly and display the correct year & Month but the third print throws an error:

Traceback (most recent call last):
File "/home/pi/SystemChecker.py", line 15, in <module>
print calendar.monthrange(cYfDateY + ',' + cYfDateM)
TypeError: monthrange() takes exactly 2 arguments (1 given)

I cannot see why it is telling me there is only 1 argument when there are clearly two there.

What am I missing?



The immediate problem is that monthrange is expecting two arguments; but you for some reason are taking the two arguments you have and joining them both into a single string. Don't do that; just pass the arguments:

calendar.monthrange(cYfDateY, cYfDateM)

The rest of the script is strange too, though. You correctly calculate yesterday's date, but then you convert it to a string, and then use the third-party arrow library to get the month and day from that string. This won't even work, since those are now strings. Why are you doing this? Why not just get the month and date you already had?

yesterday = date.today() - timedelta(1)   
cYfDateY = yesterday.year
cYfDateM = yesterday.month