I am trying to get the date of the previous month with python. Here is what i've tried:
str( time.strftime('%Y') ) + str( int(time.strftime('%m'))-1 )
However, this way is bad for 2 reasons: First it returns 20122 for the February of 2012 (instead of 201202) and secondly it will return 0 instead of 12 on January.
I have solved this trouble in bash with
echo $(date -d"3 month ago" "+%G%m%d")
I think that if bash has a built-in way for this purpose, then python, much more equipped, should provide something better than forcing writing one's own script to achieve this goal. Of course i could do something like:
if int(time.strftime('%m')) == 1:
return '12'
else:
if int(time.strftime('%m')) < 10:
return '0'+str(time.strftime('%m')-1)
else:
return str(time.strftime('%m') -1)
I have not tested this code and i don't want to use it anyway (unless I can't find any other way:/)
Thanks for your help!
Just for fun, a pure math answer using divmod. Pretty inneficient because of the multiplication, could do just as well a simple check on the number of month (if equal to 12, increase year, etc)
datetime and the datetime.timedelta classes are your friend.
Like this:
Building on bgporter's answer.
Building off the comment of @J.F. Sebastian, you can chain the
replace()
function to go back one "month". Since a month is not a constant time period, this solution tries to go back to the same date the previous month, which of course does not work for all months. In such a case, this algorithm defaults to the last day of the prior month.Output:
You should use dateutil. With that, you can use relativedelta, it's an improved version of timedelta.