693

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
5
  • 26
    General clue: if you get the error name 'timedelta' is not defined, that means that you haven't defined timedelta anywhere. Python is usually pretty informative about its error messages. Commented Jul 29, 2011 at 10:06
  • 1
    Search didn't work? All of these code examples would have helped: stackoverflow.com/search?q=python+timedelta. There appear to be over 200 questions just like this one. Commented Jul 29, 2011 at 10:08
  • 1
    possible duplicate of add days to a date in Python using loops, ranges, and slicing Commented Jul 29, 2011 at 10:11
  • 15
    You want to add five days, but then you have timedelta(days=10)…I'm confused about where the 10 came from and why it isn't 5 Commented Jan 7, 2013 at 0:53
  • with same question, exclude the Weekend means? Commented Apr 21, 2023 at 13:38

19 Answers 19

977

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)
Sign up to request clarification or add additional context in comments.

10 Comments

datetime.datetime - why twice?
importing like "from datetime import datetime, timedelta" would add readibility to the code
@paulmorriss: You are calling the strptime method on the datetime class in the datetime module, so you need to specify datetime.datetime.
Can we all agree that naming a commonly-used class the same name as the module containing it is a dumb idea? What is datetime? You can't rely on convention to know, but always have to look at the imports.
Long tail legacy problem there. it "should" be from datetime import DateTime since classes are CamelCased, but datetime precedes PEP8.
|
248

Import timedelta and date first.

from datetime import timedelta, date

And date.today() will return today's datetime, which you can then add a timedelta to it:

end_date = date.today() + timedelta(days=10)

5 Comments

datetime.date.today() instead of Date.today()
@dan-klasson It doesn't work for me, date object don't have timedelta method. What Python version are you using?
@DrTyrsa My bad. Should be: from datetime import timedelta, date; date.today() + timedelta(days=10)
I am using python 3.7. Worked for me. Thanks a lot.
from datetime import timedelta, datetime and datetime.today() would give timings (hours, ...) also
45

If you happen to already be using pandas, you can save a little space by not specifying the format:

import pandas as pd
startdate = "10/10/2011"
enddate = pd.to_datetime(startdate) + pd.DateOffset(days=5)

4 Comments

just want to note that installing pandas just for this is seriously overkill.
This was the best answer for me because I was already using pandas and didn't want to import yet another library.
I fully disagree, this format is ambiguous (for different users, 01/02/2011 could mean January 2nd or February 1st). It is better to specify the format or to use the unambiguous format YYYY-MM-DD
@Vincent fair enough; to_datetime does allow you to specify the datetime format either with the dayfirst flag or the format param
45

This might help:

from datetime import date, timedelta
date1 = date(2011, 10, 10)
date2 = date1 + timedelta(days=5)
print (date2)

1 Comment

you can also do date1 += timedelta(days=5).
19

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')

Comments

15

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

1 Comment

relativedelta is especially useful when doing operations on month year etc.
14

I guess you are missing something like that:

from datetime import timedelta

Comments

9

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

1 Comment

Good code. But your IF to test the addDays in get_date is not necessary
8

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 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.

Comments

6

You forgot to import timedelta function from datetime

This is how you can fix it:

import re
from datetime import datetime, timedelta

StartDate = "10/10/11"

Date = datetime.strptime(StartDate, "%m/%d/%y")

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

print(EndDate)

This is the output from the code above: 2012-08-03 23:13:53.485750

Comments

4

Try this:

Adding 5 days to current date.

from datetime import datetime, timedelta

current_date = datetime.now()
end_date = current_date + timedelta(days=5) # Adding 5 days.
end_date_formatted = end_date.strftime('%Y-%m-%d')
print(end_date_formatted)

subtracting 5 days from current date.

from datetime import datetime, timedelta

current_date = datetime.now()
end_date = current_date + timedelta(days=-5) # Subtracting 5 days.
end_date_formatted = end_date.strftime('%Y-%m-%d')
print(end_date_formatted)

Comments

2

I just came across this old thread:

I have checked but most of the answers are the same. I liked two answers from all these so I thought to check the efficiency of these two approaches.

First Approach: using the DateTime module Second Approach: using the panda's library

So I run the test about 10k times and The pandas library method was much slower. So I suggest using the built-in DateTime module.

from datetime import date, timedelta
import pandas as pd
import timeit

def using_datetime():
    pre_date = date(2013, 10, 10)
    day_date = pre_date + timedelta(days=5)
    return day_date

def using_pd():
    start_date = "10/10/2022"
    pd_date = pd.to_datetime(start_date)
    end_date = pd_date + pd.DateOffset(days=5)
    return end_date
    

for func in [using_datetime, using_pd]:
    print(f"{func.__name__} Time Took: ",  timeit.timeit(stmt=func, number=10000))
    
# Output 
# using_datetime Time Took:  0.009390000021085143
# using_pd Time Took:  2.1051381999859586

Comments

1

You can use it this way, It will work:

If you need only date, then:

import datetime

StartDate = "10/10/11"
Date = datetime.datetime.strptime(StartDate, "%m/%d/%y").date()
print("Date: ", Date)

EndDate = Date + datetime.timedelta(days=10)
print("EndDate: ", EndDate)

If you need date time both, then:

import datetime

StartDate = "10/10/11"
Date = datetime.datetime.strptime(StartDate, "%m/%d/%y")
print("Date: ", Date)

EndDate = Date + datetime.timedelta(days=10)
print("EndDate: ", EndDate)

Comments

1

With the module swisseph (pip install pyswisseph; import swisseph as swe), you can even handle the Julian calendar and dates outside the 1-9999AD range, while in datetime you can only work with the Gregorian calendar and at most four-digit years.

This is slower than datetime though, so if you don't need the Julian calendar or dates outside said range, it's advisable to use datetime. However, the speed is only about five times slower, compared to pandas, which is ~160 times slower! Actually, the below "plain" function, which does not verify that the dates are valid and expects year, month, day to already be in int format, can sometimes be less than 2 times slower than the datetime module.

import swisseph as swe # install with: pip install pyswisseph

CALENDARS = {b'g': swe.GREG_CAL, b'j': swe.JUL_CAL, swe.GREG_CAL: b'g', swe.JUL_CAL: b'j'}

def add_days(year, month, day, delta, calendar=b'g'): # do not verify if date is invalid
    cal = CALENDARS[calendar]
    start_julday = swe.julday(year, month, day, cal=cal)
    end_julday = start_julday + delta
    return swe.revjul(end_julday, cal=cal)[:3]

def add_days_verify(year, month, day, delta, calendar=b'g'): # raise error if date is not valid
    valid, start_julday, correct_parameters = swe.date_conversion(year, month, day, 12, cal=calendar)
    
    if not valid:
        raise ValueError('Invalid date')
    end_julday = start_julday + delta
    cal = CALENDARS[calendar]
    
    return swe.revjul(end_julday, cal=cal)[:3]

def add_days_amdate(datestr, delta, calendar=b'g', verify=True):
    month, day, year = datestr.split('/')
    if verify:
        nyear, nmonth, nday = add_days_verify(int(year), int(month), int(day), delta, calendar)
    else:
        nyear, nmonth, nday = add_days(int(year), int(month), int(day), delta, calendar)
    #return '{}/{}/{}'.format(nmonth, nday, nyear) # Python < 3.6
    return f'{nmonth}/{nday}/{nyear}'

def add_days_plain(year, month, day, delta, cal=swe.GREG_CAL):
    start_julday = swe.julday(year, month, day, cal=cal)
    end_julday = start_julday + delta
    return swe.revjul(end_julday)[:3]

# pass calendar=b'j' for Julian calendar (swe.JUL_CAL for add_days_plain)
# Examples
##>>> add_days_amdate('2/28/1900', 1, b'g')
##'3/1/1900'
##>>> add_days_amdate('2/28/1900', 1, b'j')
##'2/29/1900'
##>>> add_days_amdate('2/29/1900', 1, b'g')
##Traceback (most recent call last): ... Error
##>>> add_days_amdate('2/29/1900', 1, b'g', verify=False)
##'3/2/1900'
##>>> add_days_verify(1900, 2, 28, 1)
##(1900, 3, 1)
##>>> add_days_verify(1900, 2, 28, 1, b'j')
##(1900, 2, 29)
##>>> add_days_verify(1900, 2, 29, 1)
##Traceback (most recent call last): ... Error
##ValueError: Invalid date
##>>> add_days(1900, 2, 29, 1)
##(1900, 3, 2)
##>>> add_days(1900, 2, 29, 1, b'j')
##(1900, 3, 1)
##>>> add_days_verify(30202, 10, 28, 5) # Date after 9999
##(30202, 11, 2)
##>>> add_days_verify(-1, 12, 31, 1) # -1 is 2 BC, 0 is 1 BC, 1 is 1 AD etc.
##(0, 1, 1)


# Testing speed like AlixaProDev
import timeit

def using_swisseph_verify():
    return add_days_amdate("10/10/2022", 5)

def using_swisseph():
    return add_days_amdate("10/10/2022", 5, verify=False)

def using_swisseph_plain():
    return add_days_plain(2022, 10, 10, 5)

for func in [using_swisseph_verify, using_swisseph, using_swisseph_plain]:
    print(f"{func.__name__} Time Took: ",  timeit.timeit(stmt=func, number=10000))

A last note on speed. When I add this:

def using_swisseph():
    start_julday = swe.julday(2022, 10, 10)
    end_julday = start_julday + 5
    return swe.revjul(end_julday)[:3]

to the end of AlixaProDev's testing script and change the for loop to for func in [using_datetime, using_pd, using_swisseph]:, somethimes swisseph is even faster than datetime, but it varies a lot.

Comments

0

using timedeltas you can do:

import datetime
today=datetime.date.today()


time=datetime.time()
print("today :",today)

# One day different .
five_day=datetime.timedelta(days=5)
print("one day :",five_day)
#output - 1 day , 00:00:00


# five day extend .
fitfthday=today+five_day
print("fitfthday",fitfthday)


# five day extend .
fitfthday=today+five_day
print("fitfthday",fitfthday)
#output - 
today : 2019-05-29
one day : 5 days, 0:00:00
fitfthday 2019-06-03

Comments

0

Generally you have'got an answer now but maybe my class I created will be also helpfull. For me it solves all my requirements I have ever had in my Pyhon projects.

class GetDate:
    def __init__(self, date, format="%Y-%m-%d"):
        self.tz = pytz.timezone("Europe/Warsaw")

        if isinstance(date, str):
            date = datetime.strptime(date, format)

        self.date = date.astimezone(self.tz)

    def time_delta_days(self, days):
        return self.date + timedelta(days=days)

    def time_delta_hours(self, hours):
        return self.date + timedelta(hours=hours)

    def time_delta_seconds(self, seconds):
        return self.date + timedelta(seconds=seconds)

    def get_minimum_time(self):
        return datetime.combine(self.date, time.min).astimezone(self.tz)

    def get_maximum_time(self):
        return datetime.combine(self.date, time.max).astimezone(self.tz)

    def get_month_first_day(self):
        return datetime(self.date.year, self.date.month, 1).astimezone(self.tz)

    def current(self):
        return self.date

    def get_month_last_day(self):
        lastDay = calendar.monthrange(self.date.year, self.date.month)[1]
        date = datetime(self.date.year, self.date.month, lastDay)
        return datetime.combine(date, time.max).astimezone(self.tz)

How to use it

  1. self.tz = pytz.timezone("Europe/Warsaw") - here you define Time Zone you want to use in project
  2. GetDate("2019-08-08").current() - this will convert your string date to time aware object with timezone you defined in pt 1. Default string format is format="%Y-%m-%d" but feel free to change it. (eg. GetDate("2019-08-08 08:45", format="%Y-%m-%d %H:%M").current())
  3. GetDate("2019-08-08").get_month_first_day() returns given date (string or object) month first day
  4. GetDate("2019-08-08").get_month_last_day() returns given date month last day
  5. GetDate("2019-08-08").minimum_time() returns given date day start
  6. GetDate("2019-08-08").maximum_time() returns given date day end
  7. GetDate("2019-08-08").time_delta_days({number_of_days}) returns given date + add {number of days} (you can also call: GetDate(timezone.now()).time_delta_days(-1) for yesterday)
  8. GetDate("2019-08-08").time_delta_haours({number_of_hours}) similar to pt 7 but working on hours
  9. GetDate("2019-08-08").time_delta_seconds({number_of_seconds}) similar to pt 7 but working on seconds

Comments

0

Sometimes we need to use searching by from date & to date. If we use date__range then we need to add 1 day to to_date otherwise queryset will be empty.

Example:

from datetime import timedelta  

from_date  = parse_date(request.POST['from_date'])

to_date    = parse_date(request.POST['to_date']) + timedelta(days=1)

attendance_list = models.DailyAttendance.objects.filter(attdate__range = [from_date, to_date])

Comments

0

I already see a pandas example, but here a twist to it where you can directly import the Day class

from pandas.tseries.offsets import Day

date1 = datetime(2011, 10, 10)
date2 = date1 + 5 * Day()

Comments

-19
class myDate:

    def __init__(self):
        self.day = 0
        self.month = 0
        self.year = 0
        ## for checking valid days month and year
        while (True):
            d = int(input("Enter The day :- "))
            if (d > 31):
                print("Plz 1 To 30 value Enter ........")
            else:
                self.day = d
                break

        while (True):
            m = int(input("Enter The Month :- "))
            if (m > 13):
                print("Plz 1 To 12 value Enter ........")
            else:
                self.month = m
                break

        while (True):
            y = int(input("Enter The Year :- "))
            if (y > 9999 and y < 0000):
                print("Plz 0000 To 9999 value Enter ........")
            else:
                self.year = y
                break
    ## method for aday ands cnttract days
    def adayDays(self, n):
        ## aday days to date day
        nd = self.day + n
        print(nd)
        ## check days subtract from date
        if nd == 0: ## check if days are 7  subtracted from 7 then,........
            if(self.year % 4 == 0):
                if(self.month == 3):
                    self.day = 29
                    self.month -= 1
                    self.year = self. year
            else:
                if(self.month == 3):
                    self.day = 28
                    self.month -= 1
                    self.year = self. year
            if  (self.month == 5) or (self.month == 7) or (self.month == 8) or (self.month == 10) or (self.month == 12):
                self.day = 30
                self.month -= 1
                self.year = self. year
                   
            elif (self.month == 2) or (self.month == 4) or (self.month == 6) or (self.month == 9) or (self.month == 11):
                self.day = 31
                self.month -= 1
                self.year = self. year

            elif(self.month == 1):
                self.month = 12
                self.year -= 1    
        ## nd == 0 if condition over
        ## after subtract days to day io goes into negative then
        elif nd < 0 :   
            n = abs(n)## return positive if no is negative
            for i in range (n,0,-1): ## 
                
                if self.day == 0:

                    if self.month == 1:
                        self.day = 30
                        
                        self.month = 12
                        self.year -= 1
                    else:
                        self.month -= 1
                        if(self.month == 1) or (self.month == 3)or (self.month == 5) or (self.month == 7) or (self.month == 8) or (self.month == 10) or (self.month ==12):
                            self.day = 30
                        elif(self.month == 4)or (self.month == 6) or (self.month == 9) or (self.month == 11):
                            self.day = 29
                        elif(self.month == 2):
                            if(self.year % 4 == 0):
                                self.day == 28
                            else:
                                self.day == 27
                else:
                    self.day -= 1

        ## enf of elif negative days
        ## adaying days to DATE
        else:
            cnt = 0
            while (True):

                if self.month == 2:  # check leap year
                    
                    if(self.year % 4 == 0):
                        if(nd > 29):
                            cnt = nd - 29
                            nd = cnt
                            self.month += 1
                        else:
                            self.day = nd
                            break
                ## if not leap year then
                    else:  
                    
                        if(nd > 28):
                            cnt = nd - 28
                            nd = cnt
                            self.month += 1
                        else:
                            self.day = nd
                            break
                ## checking month other than february month
                elif(self.month == 1) or (self.month == 3) or (self.month == 5) or (self.month == 7) or (self.month == 8) or (self.month == 10) or (self.month == 12):
                    if(nd > 31):
                        cnt = nd - 31
                        nd = cnt

                        if(self.month == 12):
                            self.month = 1
                            self.year += 1
                        else:
                            self.month += 1
                    else:
                        self.day = nd
                        break

                elif(self.month == 4) or (self.month == 6) or (self.month == 9) or (self.month == 11):
                    if(nd > 30):
                        cnt = nd - 30
                        nd = cnt
                        self.month += 1

                    else:
                        self.day = nd
                        break
                ## end of month condition
        ## end of while loop
    ## end of else condition for adaying days
    def formatDate(self,frmt):

        if(frmt == 1):
            ff=str(self.day)+"-"+str(self.month)+"-"+str(self.year)
        elif(frmt == 2):
            ff=str(self.month)+"-"+str(self.day)+"-"+str(self.year)
        elif(frmt == 3):
            ff =str(self.year),"-",str(self.month),"-",str(self.day)
        elif(frmt == 0):
            print("Thanky You.....................")
            
        else:
            print("Enter Correct Choice.......")
        print(ff)
            
            

dt = myDate()
nday = int(input("Enter No. For Aday or SUBTRACT Days :: "))
dt.adayDays(nday)
print("1 : day-month-year")
print("2 : month-day-year")
print("3 : year-month-day")
print("0 : EXIT")
frmt = int (input("Enter Your Choice :: "))
dt.formatDate(frmt)

1 Comment

There is a built-in timedelta object that takes care of everything you're trying to do here, and then some.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.