Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform arithmetic operation on a date in Python?

I have a date column in csv file say Date having dates in this format 04/21/2013 and I have one more column Next_Day. In Next_Day column I want to populate the date which comes immediately after the date mentioned in date column. For eg. if date column has 04/21/2013 as date then I want 04/22/2013 in Next_Day column.

We can use +1 in excel but I don't know how to perform this in Python.

Please help me in resolving this.

like image 879
atams Avatar asked May 21 '13 12:05

atams


People also ask

Can we use arithmetic operators on date functions?

The only arithmetic operations that can be performed on datetime values are addition and subtraction. If a datetime value is the operand of addition, the other operand must be a duration.

How do you get dd mm yyyy in Python?

Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.

How different operations can be done on date and time in Python?

datetime includes two methods, strptime() and strftime(), for converting objects from strings to datetime objects and vice versa. strptime() can read strings with date and time information and convert them to datetime objects, and strftime() converts datetime objects back into strings.


1 Answers

Using datetime.timedelta

>>> import datetime >>> s = '04/21/2013' >>> d = datetime.datetime.strptime(s, '%m/%d/%Y') + datetime.timedelta(days=1) >>> print(d.strftime('%m/%d/%Y')) 04/22/2013 
like image 196
jamylak Avatar answered Sep 17 '22 18:09

jamylak