Reputation: 1260
I currently have this code to print today's date in a format I need for my program, but can't figure out how to subtract 3 months (considering some months vary in days) and return said new date in the format in place below:
import datetime
now = datetime.date.today() # create the date for today
today = '{0:%m%d%y}'.format(now).format(now)
Upvotes: 0
Views: 1162
Reputation: 103844
Given:
>>> import datetime
>>> now = datetime.date.today() # create the date for today
>>> today = '{0:%m%d%y}'.format(now)
>>> now
datetime.date(2018, 7, 13)
>>> today
'071318'
You can use calendar:
import calendar
def monthdelta(date, delta):
m, y = (date.month+delta) % 12, date.year + ((date.month)+delta-1) // 12
if not m: m = 12
d = min(date.day, calendar.monthrange(y, m)[1])
return date.replace(day=d,month=m, year=y)
>>> '{0:%m%d%y}'.format(monthdelta(now,-3))
'041318'
This is Python 3 only because of //
Upvotes: 2