Repository navigation
Add Add Months To Date and Subtract Months From Date keywords to the DateTime library - #5729
dilrukshax wants to merge 1 commit into
Conversation
…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.
There was a problem hiding this comment.
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 DateandSubtract 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-levelValueErrorfor invalid strings. Convert only from integer strings and otherwise require an actualintso 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.
| return ( | ||
| Date(date, date_format) | ||
| .add_months(int(months)) | ||
| .convert(result_format, millis=not exclude_millis) | ||
| ) |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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) | ||
| ) |
There was a problem hiding this comment.
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) | ||
| ) |
There was a problem hiding this comment.
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)}.") |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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 = 12Notice 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) |
There was a problem hiding this comment.
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.
|
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 |
Closes #4890
Summary
The
DateTimestandard library supports adding/subtracting fixed-durationtime intervals via
Add Time To Date/Subtract Time From Date, but itdrops day-precision when one wants to add calendar months - which have a
variable number of days. Issue #4890 requests an
Add Months To Datekeyword 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 arithmeticusing Python's stdlib
calendar.monthrange, no new dependencies.The day-of-month is clamped to the last valid day of the target month
Mar 31 + 1m = Apr 30. Hours/minutes/seconds/milliseconds preserved.
Public keyword
Add Months To Dateand symmetricSubtract Months From Dateexported via__all__and present in thelibdoc 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.robotatest/testdata/standard_libraries/datetime/subtract_months_from_date.robotatest/robot/standard_libraries/datetime/{add,subtract}_months_to_date.robotWhy a calendar keyword and not just expand
TimeMonths are not a fixed-duration time interval. The existing
Timeclassis built on
datetime.timedelta, which represents a fixed number ofseconds. 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
python -m robot --pythonpath src atest/testdata/standard_libraries/datetime/{add,subtract}_months_to_date.roboton CPython 3.14.
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 unrelatedget_current_date.robot"Invalid time zone" failure reproduces onmaster with the same Python version and predates this change.
no new ruff findings are introduced (the remaining DTZ*** and N999
warnings are pre-existing project-wide rules flagged on master too).
calendar.monthrangefrom 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.