在Python中为日期添加天数 [英] Adding days to a date in Python
本文介绍了在Python中为日期添加天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个日期 10/10/11(m-d-y)
,我想使用Python脚本为其添加5天。请考虑在月底也可以使用的通用解决方案。
I have a date "10/10/11(m-d-y)"
and I want to add 5 days to it using a Python script. Please consider a general solution that works on the month ends also.
我正在使用以下代码:
import re
from datetime import datetime
StartDate = "10/10/11"
Date = datetime.strptime(StartDate, "%m/%d/%y")
打印日期
->正在打印'2011-10-10 00:00:00'
现在,我要在此日期之前增加5天。我使用了以下代码:
Now I want to add 5 days to this date. I used the following code:
EndDate = Date.today()+timedelta(days=10)
哪个返回此错误:
name 'timedelta' is not defined
推荐答案
上一个答案是正确的,但这通常是更好的做法:
The previous answers are correct but it's generally a better practice to do:
import datetime
然后,您将使用 datetime.timedelta
:
Then you'll have, using datetime.timedelta
:
date_1 = datetime.datetime.strptime(start_date, "%m/%d/%y")
end_date = date_1 + datetime.timedelta(days=10)
这篇关于在Python中为日期添加天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文