4

How do I remove 3 months from the date? tried to use relativedelta, but I don't have the lib, so is there another way?

from datetime import datetime
now = datetime.now()
print("timestamp =", now)

3 Answers3

4

You can use:

import datetime

a = datetime.datetime.now()

b = a - datetime.timedelta(weeks=12)

Note that you cannot give months as inputs, but weeks and days, and smaller

Hoekieee
  • 367
  • 1
  • 15
  • 4
    Note that for May 31st it would produce a date different than OP expected - March 8th as it internally changes weeks to days, i.e. `12 weeks = 12*7 days`. It would lead to a false conclusion that a year has 364 days, equally spread. – Arn Nov 20 '19 at 11:14
2

Perhaps, subtracting with datetime.timedelta can help you estimate the date:

import datetime
datetime.datetime(2019,5,31) - datetime.timedelta(3*365.25/12)

This result is not completely accurate, as it does not account for the leap years in the usual way, however for less precise calculations within a year should suffice. If you need accuracy you will need to use the method below.

For dateutil.relativedelta, you need to first install the module with pip install python-dateutil, and then use it in the following way:

import datetime
from dateutil.relativedelta import relativedelta
datetime.datetime(2019,5,31) - relativedelta(months=3)
Arn
  • 1,898
  • 12
  • 26
0

If you want to perform complex operations on datetime objects, I can only recommend you to use the library arrow that will handle all the edge cases for you.

The documentation of this library is available here: https://arrow.readthedocs.io/en/latest/

For instance in your case:

>>> import arrow
>>> a = arrow.utcnow()
>>> a
<Arrow [2019-11-20T13:03:52.518238+00:00]>
>>> a.datetime
datetime.datetime(2019, 11, 20, 13, 3, 52, 518238, tzinfo=tzutc())
>>> b = a.shift(months=-3)
>>> b
<Arrow [2019-08-20T13:03:52.518238+00:00]>
>>> b.datetime
datetime.datetime(2019, 8, 20, 13, 3, 52, 518238, tzinfo=tzutc())

aveuiller
  • 1,511
  • 1
  • 10
  • 25