python-3.x - Python - 从今天的日期减去 3 个月,同时保持特定的日期格式
问题描述
我目前有此代码以我的程序所需的格式打印今天的日期,但无法弄清楚如何减去 3 个月(考虑到某些月份的天数不同)并以下面的格式返回所述新日期:
import datetime
now = datetime.date.today() # create the date for today
today = '{0:%m%d%y}'.format(now).format(now)
解决方案
鉴于:
>>> 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,因为//
推荐阅读
- python - xml xpath和python中的嵌套
- javascript - 使用 Column 的 react-bulma 组件导致意外令牌
- vb.net - 将 OpenPOP 附件转发到 SMTP (System.Net.Mail)
- javascript - 将字符串转换为日期对象 javascript 返回不正确的日期
- python - 在零和一的矩阵中找到 1 的位置 (i, j) 的最佳方法是什么?
- python - 从 CSV 文件更新 Django 数据库中的值时如何使用 update_or_create
- node.js - MONGODB+Node上的认证问题
- list - LiteDB - 通过 List.contains 查找数据对象
- c++ - 如何在 if 语句中最好地测试和解包 std::optional
- scala - 创建一个Fat jar来打包多个jar