Version
Python version :Python 3.6.0 :: Anaconda 4.3.1 (64-bit)
System version :Windows 10
System version :Windows 10
Code:
from datetime import datetime,timedelta
string_date = '20170727'
# Convert String to datetime object - 字串轉日期
datetime_date = datetime.strptime(string_date, "%Y%m%d").date()
# 日期的加減法
date_sub_1 = datetime_date - timedelta(1)
# Convert datetime to String - 日期轉字串
date_sub_1_string = date_sub_1.strftime("%Y-%m-%d")
print('datetime_date :',datetime_date,'\t,type :',type(datetime_date))
print('date_sub_1 :',date_sub_1,'\t,type :',type(date_sub_1))
print('date_sub_1_string :',date_sub_1_string,'\t,type :',type(date_sub_1_string))
Result:
datetime_date : 2017-07-27 ,type : <class 'datetime.date'>
date_sub_1 : 2017-07-26 ,type : <class 'datetime.date'>
date_sub_1_string : 2017-07-26 ,type : <class 'str'>