Adding 5 days to a date in Python

2019-01-02 15:20发布

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.

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'

Now I want to add 5 days to this date. I used the following code:

EndDate = Date.today()+timedelta(days=10)

Which returned this error:

name 'timedelta' is not defined

8条回答
忆尘夕之涩
2楼-- · 2019-01-02 15:36

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
查看更多
浮光初槿花落
3楼-- · 2019-01-02 15:47

The previous answers are correct but it's generally a better practice to do:

import datetime

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)
查看更多
低头抚发
4楼-- · 2019-01-02 15:52

I guess you are missing something like that:

from datetime import timedelta
查看更多
栀子花@的思念
5楼-- · 2019-01-02 15:56

Here is another method to add days on date using dateutil's 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

After 5 Days: 30/06/2015 15:56:09

查看更多
其实,你不懂
6楼-- · 2019-01-02 15:56

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.

from datetime import datetime as DateTime, timedelta as TimeDelta

So you can do the following, which I think it is clear.

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.

查看更多
高级女魔头
7楼-- · 2019-01-02 16:00

Import timedelta first.

from datetime import timedelta

And Date.today() will return today's datetime, may be you want

EndDate = Date + timedelta(days=10)
查看更多
登录 后发表回答