datetime字符串转日期, 日期转字符串

import datetime
data_date = “20200421”
days = -3

date_str = data_date[:-4] + ‘-’ + data_date[-4:-2] + ‘-’ + data_date[-2:]
#‘2020-04-21’

date_p = datetime.datetime.strptime(date_str, ‘%Y-%m-%d’).date()
#datetime.date(2020, 4, 21) #字符串转日期

his_date = date_p + datetime.timedelta(days=days)
#datetime.date(2020, 4, 18)

his_date.strftime("%Y%m%d")
#"‘20200418’" # 日期转字符串

his_date.strftime(’%Y-%m-%d’)
#‘2020-04-18’

你可能感兴趣的:(python学习)