Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to accurately minus X month on a date in Python?

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?

like image 931
Mars Lee Avatar asked Mar 10 '16 05:03

Mars Lee


People also ask

How do you subtract months from datetime?

Just substract a month by 'adding` -1: var lastmonth = DateTime. Today. AddMonths(-1);

How do pandas subtract months?

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.

How do you subtract 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 a date from a string in Python?

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.


1 Answers

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.

like image 69
Girish Jadhav Avatar answered Oct 01 '22 17:10

Girish Jadhav