Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding days to a date in Python

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 
like image 637
MuraliKrishna Avatar asked Jul 29 '11 09:07

MuraliKrishna


2 Answers

Import timedelta and date first.

from datetime import timedelta, date 

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

EndDate = date.today() + timedelta(days=10) 
like image 27
DrTyrsa Avatar answered Oct 08 '22 00:10

DrTyrsa


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) 
like image 123
Botond Béres Avatar answered Oct 07 '22 23:10

Botond Béres