日期偏移
import datetime from dateutil.relativedelta import relativedelta def date_add(date, seconds=0, minutes=0, hours=0, days=0, months=0, years=0): date = date + datetime.timedelta(seconds=seconds, minutes=minutes, hours=hours, days=days) date = date + relativedelta(months=months) date = datetime.datetime(year=date.year + years, month=date.month, day=date.day, hour=date.hour, minute=date.minute, second=date.second) return date now = datetime.datetime.now() date = date_add(now, months=-13) print(date)
获取月份的第一天和最后一天
import calendar import datetime now = datetime.date.today() this_month_start = datetime.datetime(now.year, now.month, 1) this_month_end = datetime.datetime(now.year, now.month, calendar.monthrange(now.year, now.month)[1]) print(this_month_start) print(this_month_end)