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 )
<
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.
from datetime import datetime, timedelta
d = datetime(2012, 3, 31) # A problem date as an example
# last day of last month
one_month_ago = (d.replace(day=1) - timedelta(days=1))
try:
# try to go back to same day last month
one_month_ago = one_month_ago.replace(day=d.day)
except ValueError:
pass
print("one_month_ago: {0}".format(one_month_ago))
Output:
one_month_ago: 2012-02-29 00:00:00