Skip to content

Commit

Permalink
Add timedelta support to timestr_to_secs.
Browse files Browse the repository at this point in the history
Fixes #4521.

Also mention that `accept_plain_values` is deprecated (#4522).
  • Loading branch information
pekkaklarck committed Oct 28, 2022
1 parent e4bdf02 commit e1ccafe
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
14 changes: 13 additions & 1 deletion src/robot/utils/robottime.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

import re
import time
from datetime import timedelta

from .normalizing import normalize
from .misc import plural_or_not
Expand All @@ -39,7 +40,16 @@ def _float_secs_to_secs_and_millis(secs):


def timestr_to_secs(timestr, round_to=3, accept_plain_values=True):
"""Parses time like '1h 10s', '01:00:10' or '42' and returns seconds."""
"""Parses time strings like '1h 10s', '01:00:10' and '42' and returns seconds.
Time can also be given as an integer or float or, starting from RF 6.0.1,
as a `timedelta` instance.
The result is rounded according to the `round_to` argument.
Use `round_to=None` to disable rounding altogether.
`accept_plain_values` is considered deprecated and should not be used.
"""
if is_string(timestr) or is_number(timestr):
if accept_plain_values:
converters = [_number_to_secs, _timer_to_secs, _time_string_to_secs]
Expand All @@ -49,6 +59,8 @@ def timestr_to_secs(timestr, round_to=3, accept_plain_values=True):
secs = converter(timestr)
if secs is not None:
return secs if round_to is None else round(secs, round_to)
if isinstance(timestr, timedelta):
return timestr.total_seconds()
raise ValueError("Invalid time string '%s'." % timestr)


Expand Down
6 changes: 5 additions & 1 deletion utest/utils/test_robottime.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import unittest
import re
import time
from datetime import datetime
from datetime import datetime, timedelta

from robot.utils.asserts import (assert_equal, assert_raises_with_msg,
assert_true, assert_not_none)
Expand Down Expand Up @@ -154,6 +154,10 @@ def test_timestr_to_secs_with_timer_string(self):
exp += 0.5 if inp[0] != '-' else -0.5
assert_equal(timestr_to_secs(inp), exp, inp)

def test_timestr_to_secs_with_timedelta(self):
assert_equal(timestr_to_secs(timedelta(minutes=1)), 60)
assert_equal(timestr_to_secs(timedelta(microseconds=1000)), 0.001)

def test_timestr_to_secs_custom_rounding(self):
secs = 0.123456789
for round_to in 0, 1, 6:
Expand Down

0 comments on commit e1ccafe

Please sign in to comment.