Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract dates with python

Tags:

Today =

today = datetime.datetime.now().strftime("%Y%m%d") 

90days ago

DD = datetime.timedelta(days=-90) 

How do I get today - DD, or 90days ago?

like image 857
Merlin Avatar asked Feb 01 '11 14:02

Merlin


People also ask

How do you add or subtract days from a date in Python?

For adding or subtracting Date, we use something called timedelta() function which can be found under the DateTime class. It is used to manipulate Date, and we can perform arithmetic operations on dates like adding or subtracting.

How do I subtract 7 days from a date in Python?

You can subtract a day from a python date using the timedelta object. You need to create a timedelta object with the amount of time you want to subtract. Then subtract it from the date.

How do you subtract two days from a date in Python?

You can use simple date arithmetic to find the number of days between two dates in Python. Define the 2 dates between which you want to find the difference in days. Then subtract these dates to get a timedelta object and examine the day's property of this object to get the required result.

Can you subtract dates in Pandas?

The timedelta function allows you to perform date addition and date subtraction calculations that can add or subtract specified numbers of days from a date and return a new date before or after the original date.


2 Answers

You should be able to subtract time deltas from datetime objects.

today = datetime.datetime.now() DD = datetime.timedelta(days=90) earlier = today - DD earlier_str = earlier.strftime("%Y%m%d") 
like image 71
Joshua Strouse Avatar answered Sep 19 '22 14:09

Joshua Strouse


Just subtract a timedelta from a datetime:

>>> import datetime >>> today = datetime.datetime.today() >>> DD = datetime.timedelta(days=90) >>> today - DD datetime.datetime(2010, 11, 3, 9, 56, 20, 924224) 

(or if you want to use a negative timedelta like you did there, add them:

>>> DD = datetime.timedelta(days=-90) >>> today + DD datetime.datetime(2010, 11, 3, 9, 56, 20, 924224) 
like image 20
bgporter Avatar answered Sep 19 '22 14:09

bgporter