Skip to content

Add Add Months To Date and Subtract Months From Date keywords to the DateTime library - #5729

Closed
dilrukshax wants to merge 1 commit into
robotframework:masterfrom
dilrukshax:feat/datetime-add-months-4890
Closed

dilrukshax wants to merge 1 commit into
robotframework:masterfrom
dilrukshax:feat/datetime-add-months-4890

Conversation

@dilrukshax

Copy link
Copy Markdown

Closes #4890

Summary

The DateTime standard library supports adding/subtracting fixed-duration
time intervals via Add Time To Date / Subtract Time From Date, but it
drops day-precision when one wants to add calendar months - which have a
variable number of days. Issue #4890 requests an Add Months To Date
keyword so users can write things like:

```robot
${one_month_later}= Add Months To Date ${current_date} 1
```

This change adds:

  • Date.add_months(months) helper, performing calendar-month arithmetic
    using Python's stdlib calendar.monthrange, no new dependencies.
    The day-of-month is clamped to the last valid day of the target month

    • e.g. Jan 31 + 1m = Feb 29 in a leap year (or Feb 28 otherwise);
      Mar 31 + 1m = Apr 30. Hours/minutes/seconds/milliseconds preserved.
  • Public keyword Add Months To Date and symmetric
    Subtract Months From Date exported via __all__ and present in the
    libdoc index. They follow the same argument conventions as
    Add Time To Date (date, amount, result_format, exclude_millis,
    date_format).

  • Acceptance test data + runner suites:

    • atest/testdata/standard_libraries/datetime/add_months_to_date.robot
    • atest/testdata/standard_libraries/datetime/subtract_months_from_date.robot
    • atest/robot/standard_libraries/datetime/{add,subtract}_months_to_date.robot

Why a calendar keyword and not just expand Time

Months are not a fixed-duration time interval. The existing Time class
is built on datetime.timedelta, which represents a fixed number of
seconds. Modeling "1 month" as 30.44 days would not give users the
calendar semantics they expect (e.g. Jan 31 + 1m should reach end of Feb,
not Mar 2). The new keyword intentionally stays calendar-aware and
end-of-month clamping keeps days monotonic.

Verification

  • All 17 new acceptance tests pass with python -m robot --pythonpath src atest/testdata/standard_libraries/datetime/{add,subtract}_months_to_date.robot
    on CPython 3.14.
  • Existing add_time_to_date, subtract_time_from_date,
    get_current_date, convert_date_result_format, convert_date_input_format,
    convert_time_* suites are unchanged. The single unrelated
    get_current_date.robot "Invalid time zone" failure reproduces on
    master with the same Python version and predates this change.
  • Followed CONTRIBUTING.rst: ruff and black run on the modified file;
    no new ruff findings are introduced (the remaining DTZ*** and N999
    warnings are pre-existing project-wide rules flagged on master too).
  • No third-party dependencies added - the implementation uses
    calendar.monthrange from the standard library.

Follows style guidance from CONTRIBUTING.rst. Happy to adjust naming or
split end-of-month clamping into its own configurable argument if
maintainers prefer.

…keywords

Closes #4890

The DateTime standard library supported only fixed-duration arithmetic
with `Add Time To Date` (hours, days, weeks, ...). Adding calendar
months - which have a variable number of days - was not possible,
which the issue requested as `Add Months To Date`.

This commit:

- Adds a `Date.add_months(months)` helper that performs calendar-month
  arithmetic using Python's `calendar.monthrange` to clamp the day to
  the last valid day of the target month. For example Jan 31 + 1m
  yields Feb 29 in a leap year (or Feb 28 otherwise); Mar 31 + 1m
  yields Apr 30. Hours/minutes/seconds/milliseconds are preserved.

- Adds the public keyword `Add Months To Date` and the symmetric
  `Subtract Months From Date`, both exported via `__all__` and added
  to the libdoc index. Both follow the same argument conventions as
  `Add Time To Date` (date, amount, result_format, exclude_millis,
  date_format).

- Adds acceptance test suites:
    atest/testdata/standard_libraries/datetime/add_months_to_date.robot
    atest/testdata/standard_libraries/datetime/subtract_months_from_date.robot
  with their runner suites at
    atest/robot/standard_libraries/datetime/add_months_to_date.robot
    atest/robot/standard_libraries/datetime/subtract_months_from_date.robot

All 17 new acceptance tests pass. The existing
`add_time_to_date` / `subtract_time_from_date` / `get_current_date`
suites are unaffected (the lone pre-existing `Invalid time zone`
failure in `get_current_date.robot` reproduces on master with the
same Python version and is unrelated).

End-of-month clamp deliberately avoids `dateutil.relativedelta` to
keep the DateTime standard library third-party-dependency-free, as in
the rest of the codebase.
Copilot AI review requested due to automatic review settings August 1, 2026 07:29

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR extends Robot Framework’s DateTime standard library with calendar-month arithmetic, enabling month-based date adjustments that preserve time components and apply end-of-month clamping semantics.

Changes:

  • Added Date.add_months() helper implementing calendar-month addition/subtraction with end-of-month clamping.
  • Introduced new public keywords Add Months To Date and Subtract Months From Date (exported via __all__).
  • Added acceptance test data and runner suites covering month arithmetic, leap years, and negative deltas.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
src/robot/libraries/DateTime.py Adds month-arithmetic helper and exposes new public keywords for month-based date operations.
atest/testdata/standard_libraries/datetime/add_months_to_date.robot Acceptance tests for Add Months To Date, including clamping and cross-year behavior.
atest/testdata/standard_libraries/datetime/subtract_months_from_date.robot Acceptance tests for Subtract Months From Date, including leap/non-leap clamping.
atest/robot/standard_libraries/datetime/add_months_to_date.robot Runner suite wiring for the new add-months acceptance tests.
atest/robot/standard_libraries/datetime/subtract_months_from_date.robot Runner suite wiring for the new subtract-months acceptance tests.
Suppressed comments (1)

src/robot/libraries/DateTime.py:601

  • Same as Add Months To Date: -int(months) can silently truncate floats (1.9 -> -1) and exposes a low-level ValueError for invalid strings. Convert only from integer strings and otherwise require an actual int so callers don’t get surprising results.
    return (
        Date(date, date_format)
        .add_months(-int(months))
        .convert(result_format, millis=not exclude_millis)
    )

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +560 to +564
return (
Date(date, date_format)
.add_months(int(months))
.convert(result_format, millis=not exclude_millis)
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's safe to simply replace int(months) with months. Our automatic argument conversion makes sure the value is an integer when used with Robot. If someone uses this programmatically, they should just pass an integer as the type hint suggest.

@pekkaklarck pekkaklarck left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Implementation looks good to me, but there are some things that can still be improved. Keyword docs should also get New in Robot Framework 7.5. notes at the end.

It would also be great if you could convert documentation to Markdown and take the new argument documentation syntax into use. We are doing that with all standard libraries (see #5709) and there's already a PR about converting existing DateTime docs that I try to get merged still today. If you don't have time for doc updates, we can do that separately after this PR has been merged.

I didn't look at the new test too thoroughly, but I'll do that once the above things are handled.

elapsed_time_to_string,
secs_to_timestr,
timestr_to_secs,
type_name,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To avoid wasting too much vertical space, we don't format normal imports so that each one is on its own line. That is handled automatically if you run invoke format.

Date(date, date_format)
.add_months(int(months))
.convert(result_format, millis=not exclude_millis)
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current method chaining is pretty complicated and I'm afraid automatic formatter (invoke format) will mess it up. If that happens, change the code to this is probably the best solution:

date = Date(date, date_format).add_months(months)
return date.convert(result_format, millis=not exclude_millis)

Date(date, date_format)
.add_months(-int(months))
.convert(result_format, millis=not exclude_millis)
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As already noted above, the int conversion is unnecessary and splitting method chaining can be a good idea.


def add_months(self, months: int) -> "Date":
if not isinstance(months, int):
raise TypeError(f"Months must be an integer, got {type_name(months)}.")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can expect the value to be int. No need for extra type validation.

dt = self.datetime
total = dt.year * 12 + (dt.month - 1) + months
year, zero_based_month = divmod(total, 12)
month = zero_based_month + 1

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Calculating total months feels unnecessary and how month becoming zero is prevented is somewhat complicated. I believe this approach would be a bit cleaner:

year_increment, month = divmod(dt.month + months, 12)
year = dt.year + year_increment
if month == 0:
    year -= 1
    month = 12

Notice that I haven't tested the above thoroughly, so I may have missed some corner cases.

# Clamp the day to the last valid day of the target month so that
# adding a month to e.g. Jan 31 yields Feb 28/29 (end-of-month clamp).
last_day = calendar.monthrange(year, month)[1]
day = min(dt.day, last_day)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree that best way to handle the situation where the day is too big for the month is picking up the last valid day. I was thinking about catching ValueError caused by an invalid day and decrementing the day by one until it is valid, but getting the last day with the strangely named calendar.monthrange is much better. As a style issue, I'd probably use

_, last_day = calendar.monthrane(year, month)
return Data(..., day=min(dt.day, last_day))

I'm also not sure is the comment necessary. Perhaps add_months should get a docstring where this behavior is explained instead.

@dilrukshax dilrukshax closed this by deleting the head repository Aug 4, 2026
@pekkaklarck

Copy link
Copy Markdown
Member

Why did you close this @dilrukshax? The overall approach looked fine.

I've been thinking it could be better to add months, and possibly years, support to Add Time To Date and Subtract Time From Date keywords instead of adding new keywords. I'll comment the original issue about that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

DateTime: Support adding months and yeards to dates

3 participants