So this code what I want:
import datetime
d = datetime.date.today()
three_months_ago = d - timedelta(months=3)
However, as we know, the 'months' param does not exist in timedelta.
I admit I can program like this to achieve the goal:
if d.month > 3:
three_months_ago = datetime.date(d.year, d.month-3, d.day)
else:
three_months_ago = datetime.date(d.year-1, d.month-3+12, d.day)
But this seems really stupid...
Can you guys tell me how to realize this smartly?
Just substract a month by 'adding` -1: var lastmonth = DateTime. Today. AddMonths(-1);
Subtract months from a date in Python using Pandas Pandas provide a class DateOffset, to store the duration or interval information. It is mostly used to increment or decrement a timestamp. It can be used with datetime module to to subtract N months from a date.
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.
Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format . To get the difference between two dates, subtract date2 from date1. A result is a timedelta object.
This could help:
>>>from dateutil.relativedelta import relativedelta
>>>import datetime
>>>datetime.date.today()
datetime.date(2016, 3, 10)
>>>datetime.date.today() - relativedelta(months=3)
datetime.date(2015, 12, 10)
You can use relativedelta() to add or subtract weeks and years too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With