-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.

jerome
  • 2,029
  • 4
  • 38
  • 58
  • 1
    You could try with `dateutil.relativedelta` module. – DainDwarf Feb 12 '16 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? – dhke Feb 12 '16 at 10:40
  • 1
    Yes that is it, I only want to change the month value without changing days or something else. – jerome Feb 12 '16 at 10:40
  • So what day is nine months before November 30? – khelwood Feb 12 '16 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. – jerome Feb 12 '16 at 10:48
  • @khelwood Depends on your notion. `dateutil.relativedelta` clamps to the month end, i.e. *nine months before Nov 30* is either *Feb 28* or *Feb 29*. – dhke Feb 12 '16 at 10:49
  • your variable "ts" does it means current time in seconds – Transformer Feb 12 '16 at 11:33
  • @dhke Not on _my_ notion. On the OP's. That is why I was asking the OP. – khelwood Feb 12 '16 at 16:48
  • @khelwood Please take that *your* as detached from the addressee meaning "whatever the person having to solve the problem needs". – dhke Feb 12 '16 at 16:58

1 Answers1

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)
dhke
  • 15,008
  • 2
  • 39
  • 56