首页 > 解决方案 > Python - 从今天的日期减去 3 个月,同时保持特定的日期格式

问题描述

我目前有此代码以我的程序所需的格式打印今天的日期,但无法弄清楚如何减去 3 个月(考虑到某些月份的天数不同)并以下面的格式返回所述新日期:

import datetime
now = datetime.date.today() # create the date for today
today = '{0:%m%d%y}'.format(now).format(now) 

标签: python-3.x

解决方案


鉴于:

>>> 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'

您可以使用日历:

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'

这只是 Python 3,因为//


推荐阅读