引用模块:
from datetime import datetime,timedelta
from dateutil.relativedelta import relativedelta
1、当前时间
today = datetime.now()
Out[1]: datetime.datetime(2020, 7, 24, 9, 46, 10, 474816)
格式化输出'yyyy-mm-dd'
dt = datetime.now().strftime('%Y-%m-%d')
Out[2]: '2020-07-24'
2、天数加减
day_ago = (datetime.strptime(dt, '%Y-%m-%d')+timedelta(days=+7)).strftime('%Y-%m-%d')
Out[3]: '2020-07-31' #days = 加减时间可替换
3、月份加减
month_ago = (datetime.strptime(dt, '%Y-%m-%d') + relativedelta(months=+1)).strftime('%Y-%m-%d')
Out[4]: '2020-08-24'
4、当月第一天
dt = datetime.now().date()
Out[5]: datetime.date(2020, 7, 24)
this_month_start = datetime(dt.year,dt.month, 1).strftime('%Y-%m-%d')
Out[6]: '2020-07-01'
5、本周周一的日期
today = datetime.now()
monday = (today - timedelta(today.weekday()).strftime('%Y-%m-%d')