本文翻译自:Adding 5 days to a date in Python
I have a date "10/10/11(mdy)"
and I want to add 5 days to it using a Python script. 我的日期为"10/10/11(mdy)"
,我想使用Python脚本为其添加5天。 Please consider a general solution that works on the month ends also. 请考虑在月底也可以使用的一般解决方案。
I am using following code: 我正在使用以下代码:
import re
from datetime import datetime
StartDate = "10/10/11"
Date = datetime.strptime(StartDate, "%m/%d/%y")
print Date
-> is printing '2011-10-10 00:00:00'
print Date
->正在打印'2011-10-10 00:00:00'
Now I want to add 5 days to this date. 现在,我想在此日期之前增加5天。 I used the following code: 我使用以下代码:
EndDate = Date.today()+timedelta(days=10)
Which returned this error: 哪个返回此错误:
name 'timedelta' is not defined
#1楼
参考:https://stackoom.com/question/SpSq/在Python中为日期添加-天
#2楼
If you happen to already be using pandas , you can save a little space by not specifying the format: 如果您碰巧已经在使用pandas ,则可以通过不指定格式来节省一些空间:
import pandas as pd
startdate = "10/10/2011"
enddate = pd.to_datetime(startdate) + pd.DateOffset(days=5)
#3楼
Here is a function of getting from now + specified days 这是从现在开始+指定天数的功能
import datetime
def get_date(dateFormat="%d-%m-%Y", addDays=0):
timeNow = datetime.datetime.now()
if (addDays!=0):
anotherTime = timeNow + datetime.timedelta(days=addDays)
else:
anotherTime = timeNow
return anotherTime.strftime(dateFormat)
Usage: 用法:
addDays = 3 #days
output_format = '%d-%m-%Y'
output = get_date(output_format, addDays)
print output
#4楼
Here is another method to add days on date using dateutil's relativedelta . 这是另一种使用dateutil的relativedelta添加日期的方法。
from datetime import datetime
from dateutil.relativedelta import relativedelta
print 'Today: ',datetime.now().strftime('%d/%m/%Y %H:%M:%S')
date_after_month = datetime.now()+ relativedelta(days=5)
print 'After 5 Days:', date_after_month.strftime('%d/%m/%Y %H:%M:%S')
Output: 输出:
Today: 25/06/2015 15:56:09 今天:25/06/2015 15:56:09
After 5 Days: 30/06/2015 15:56:09 5天后:30/06/2015 15:56:09
#5楼
In order to have have a less verbose code , and avoid name conflicts between datetime and datetime.datetime , you should rename the classes with CamelCase names. 为了减少冗长的代码 ,并避免datetime和datetime.datetime之间的 名称冲突 ,应使用CamelCase名称重命名这些类。
from datetime import datetime as DateTime, timedelta as TimeDelta
So you can do the following, which I think it is clearer. 因此,您可以执行以下操作,我认为这更清楚。
date_1 = DateTime.today()
end_date = date_1 + TimeDelta(days=10)
Also, there would be no name conflict if you want to import datetime
later on. 另外,如果您以后要import datetime
时间,则不会发生名称冲突 。
#6楼
If you want add days to date now, you can use this code 如果要立即添加日期,可以使用此代码
from datetime import datetime
from datetime import timedelta
date_now_more_5_days = (datetime.now() + timedelta(days=5) ).strftime('%Y-%m-%d')