本文翻譯自: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')