如何在
python中将我的日期字符串转换为datetime.timedelta()?
我有这个代码:
import datetime date_select = '2011-12-1' delta = datetime.timedelta(days=1) target_date = date_select + delta print target_date
提前致谢 …
解决方法
您不会将date_select转换为timedelta,而是需要一个datetime对象,可以将其添加到timedelta以生成更新的datetime对象:
from datetime import datetime,timedelta date_select = datetime.strptime('2011-12-1','%Y-%m-%d') delta = timedelta(days=1) target_date = date_select + delta print target_date
或者,如果您愿意,不需要…导入…导入行:
import datetime # <- LOOK HERE,same as in your example date_select = datetime.datetime.strptime('2011-12-1','%Y-%m-%d') delta = datetime.timedelta(days=1) target_date = date_select + delta print target_date