-1

I would like to substract months from a timestamp in second. Here is what I'm doing:

>>> ts = 1454284800
>>> date_object = datetime.datetime.strptime(time.strftime('%Y%m%d', time.gmtime(1454284800)), '%Y%m%d')
>>> date_object
datetime.datetime(2016, 2, 1, 0, 0)
>>> date_substract = date_object - datetime.timedelta(9*365/12.0)
>>> date_substract
datetime.datetime(2015, 5, 3, 6, 0)
>>> 

It depends on the value for the number of months I want to substract, but for 9 months for exemple, days datetime.datetime(2015, 5, 3, 6, 0) are wrong. Is there a better way to substract months, which would only change number of months and not days as well.

Thanks in advance.

9
  • 1
    You could try with dateutil.relativedelta module. Commented Feb 12, 2016 at 10:38
  • Care to elaborate your goal? A month isn't a fixed timespan, but varies with the month in question. Do you want the same day of month but nine months earlier? Commented Feb 12, 2016 at 10:40
  • 1
    Yes that is it, I only want to change the month value without changing days or something else. Commented Feb 12, 2016 at 10:40
  • So what day is nine months before November 30? Commented Feb 12, 2016 at 10:43
  • I only want to substract months days will always be 1 actually, if i'm in months 11 and substract 9 months I want to be in months 2 and day 1. Commented Feb 12, 2016 at 10:48

1 Answer 1

2

As suggested by @DainDwarf, dateutil.relativedelta seems to be your friend. It calculates a date relative to another date value.

It handles the tricky cases (e.g. a month before March 31st), but you need to check that the resolution meets your requirements

date = datetime.datetime(year=2016, month=3, day=31)
date + dateutil.relativedelta.relativedelta(date, months=-1)
=> datetime.datetime(2016, 2, 29, 0, 0)
Sign up to request clarification or add additional context in comments.

1 Comment

It is a solution but I have to install this module.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.