I would like to parse dates in a script and I was wondering if there is an equivalent of the:
relativedelta(days=1, weekday=MO)
but for months?
For now, I extract the month number in my text and compare it to the document's creation date (and month). However, this is quite long and repetitive (and I have to do it for future tenses, present tenses and past tenses)...
Adding relativedelta(month=2)
to a datetime
object will give you the same date and time, except in February. If this creates a non-existent date, the date will be truncated at the last existing date, e.g.:
from datetime import datetime
from dateutil.relativedelta import relativedelta
print(datetime(2015, 3, 30) + relativedelta(month=2)) # 2015-02-28 00:00:00
As explained in the relativedelta documentation:
year, month, day, hour, minute, second, microsecond:
Absolute information (argument is singular); adding or subtracting a relativedelta with absolute information does not perform an aritmetic operation, but rather REPLACES the corresponding value in the original datetime with the value(s) in relativedelta.
All the "singular" arguments are processed as "set this component of the thing I'm being added to/subtracted from to this value", whereas the plural versions of the same arguments say "Add/subtract this number to/from this component".
Note that the relativedelta documentation also lays out the order that each component is applied, but suffice to say that absolute values are applied before relative values, so relativedelta(month=3, months=2)
will set the month to March, then add 2 months (so, basically, it's equivalent to relativedelta(month=5)
).