比較省事的辦法是用time模塊的strptime方法來解析日期字符串成為時間對象,然後再把年月日部分提取出來,最後生成datetime.date對象。
#?方法1,?用time模塊的strptime方法來解析日期字符串成為時間對象import?time,?datetime
date_str?=?'2017-10-19'
fmt?=?'%Y-%m-%d'
time_tuple?=?time.strptime(date_str,?fmt)
year,?month,?day?=?time_tuple[:3]
a_date?=?datetime.date(year,?month,?day)
print(a_date,?type(a_date))
#?方法2,?直接把日期字符串拆分轉換成?年/月/日?對應的整數
import?datetime
date_str?=?'2017-10-19'
print(datetime.date(*map(int,?date_str.split('-'))))