datetime.timedelta()

import datetime
dt = datetime.datetime
now = dt.now()

now.strftime("%Y-%m-%d %H:%M:%S")
'2020-10-26 09:53:49'

#  问100天前 是几月记号 星期几,这个时候就可以使用timedelta 快速方便的算出
now - datetime.timedelta(days=100)    
2020-07-18 09:53:49.708843

(now - datetime.timedelta(days=100)).strftime("%Y-%m-%d %H:%M:%S")   #  转字符串
'2020-07-18 09:53:49'

weeks = ["星期一","星期二","星期三","星期四","星期五","星期六","星期日"]
weeks[(now - datetime.timedelta(days=100)).weekday()]     #  计算周几
'星期六'
datetime.timedelta()_第1张图片
#  同理 可以计算出100天后的日期
now + datetime.timedelta(days=100)    
datetime.datetime(2021, 2, 3, 9, 53, 49, 708843)
 
(now + datetime.timedelta(days=100)).strftime("%Y-%m-%d %H:%M:%S")    # 转字符串
'2021-02-03 09:53:49'

weeks[(now + datetime.timedelta(days=100)).weekday()]
'星期三'
datetime.timedelta()_第2张图片
# 计算 天 时 分 秒
now + datetime.timedelta(+3)  #  3天后
(now + datetime.timedelta(+3)).strftime("%Y-%m-%d %H:%M:%S") 
'2020-10-29 09:53:49'

(now + datetime.timedelta(-3)).strftime("%Y-%m-%d %H:%M:%S")  #  3天前
'2020-10-23 09:53:49'

(now + datetime.timedelta(hours=3)).strftime("%Y-%m-%d %H:%M:%S")  # 3小时后
'2020-10-26 12:53:49'

(now + datetime.timedelta(minutes= -53)).strftime("%Y-%m-%d %H:%M:%S")  #  53分钟前
'2020-10-26 09:00:49'

(now - datetime.timedelta(seconds=48)).strftime("%Y-%m-%d %H:%M:%S")  #  48秒前
'2020-10-26 09:53:01'

(now - datetime.timedelta(hours=1, seconds=1, days=1)).strftime("%Y-%m-%d %H:%M:%S")  #  1天1小时1秒 前
'2020-10-25 08:53:48'

你可能感兴趣的:(Python,python)