Skip to content

robot.utils.robottime

timestr_to_secs

timestr_to_secs(timestr, round_to=3)

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.

Source code in src/robot/utils/robottime.py
def timestr_to_secs(timestr, round_to=3):
    """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.
    """
    if is_string(timestr) or is_number(timestr):
        converters = [_number_to_secs, _timer_to_secs, _time_string_to_secs]
        for converter in converters:
            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(f"Invalid time string '{timestr}'.")

secs_to_timestr

1
2
3
secs_to_timestr(
    secs: int | float | timedelta, compact=False
) -> str

Converts time in seconds to a string representation.

Returned string is in format like '1 day 2 hours 3 minutes 4 seconds 5 milliseconds' with following rules:

  • Time parts having zero value are not included (e.g. '3 minutes 4 seconds' instead of '0 days 0 hours 3 minutes 4 seconds')
  • Hour part has a maximum of 23 and minutes and seconds both have 59 (e.g. '1 minute 40 seconds' instead of '100 seconds')

If compact has value 'True', short suffixes are used. (e.g. 1d 2h 3min 4s 5ms)

Source code in src/robot/utils/robottime.py
def secs_to_timestr(secs: 'int|float|timedelta', compact=False) -> str:
    """Converts time in seconds to a string representation.

    Returned string is in format like
    '1 day 2 hours 3 minutes 4 seconds 5 milliseconds' with following rules:

    - Time parts having zero value are not included (e.g. '3 minutes 4 seconds'
      instead of '0 days 0 hours 3 minutes 4 seconds')
    - Hour part has a maximum of 23 and minutes and seconds both have 59
      (e.g. '1 minute 40 seconds' instead of '100 seconds')

    If compact has value 'True', short suffixes are used.
    (e.g. 1d 2h 3min 4s 5ms)
    """
    if isinstance(secs, timedelta):
        secs = secs.total_seconds()
    return _SecsToTimestrHelper(secs, compact).get_value()

format_time

1
2
3
4
5
6
7
format_time(
    timetuple_or_epochsecs,
    daysep="",
    daytimesep=" ",
    timesep=":",
    millissep=None,
)

Deprecated in Robot Framework 7.0. Will be removed in Robot Framework 8.0.

Source code in src/robot/utils/robottime.py
def format_time(timetuple_or_epochsecs, daysep='', daytimesep=' ', timesep=':',
                millissep=None):
    """Deprecated in Robot Framework 7.0. Will be removed in Robot Framework 8.0."""
    warnings.warn("'robot.utils.format_time' is deprecated and will be "
                  "removed in Robot Framework 8.0.")
    if is_number(timetuple_or_epochsecs):
        timetuple = _get_timetuple(timetuple_or_epochsecs)
    else:
        timetuple = timetuple_or_epochsecs
    daytimeparts = ['%02d' % t for t in timetuple[:6]]
    day = daysep.join(daytimeparts[:3])
    time_ = timesep.join(daytimeparts[3:6])
    millis = millissep and '%s%03d' % (millissep, timetuple[6]) or ''
    return day + daytimesep + time_ + millis

get_time

get_time(format='timestamp', time_=None)

Return the given or current time in requested format.

If time is not given, current time is used. How time is returned is determined based on the given 'format' string as follows. Note that all checks are case-insensitive.

  • If 'format' contains word 'epoch' the time is returned in seconds after the unix epoch.
  • If 'format' contains any of the words 'year', 'month', 'day', 'hour', 'min' or 'sec' only selected parts are returned. The order of the returned parts is always the one in previous sentence and order of words in 'format' is not significant. Parts are returned as zero padded strings (e.g. May -> '05').
  • Otherwise (and by default) the time is returned as a timestamp string in format '2006-02-24 15:08:31'
Source code in src/robot/utils/robottime.py
def get_time(format='timestamp', time_=None):
    """Return the given or current time in requested format.

    If time is not given, current time is used. How time is returned is
    determined based on the given 'format' string as follows. Note that all
    checks are case-insensitive.

    - If 'format' contains word 'epoch' the time is returned in seconds after
      the unix epoch.
    - If 'format' contains any of the words 'year', 'month', 'day', 'hour',
      'min' or 'sec' only selected parts are returned. The order of the returned
      parts is always the one in previous sentence and order of words in
      'format' is not significant. Parts are returned as zero padded strings
      (e.g. May -> '05').
    - Otherwise (and by default) the time is returned as a timestamp string in
      format '2006-02-24 15:08:31'
    """
    time_ = int(time.time() if time_ is None else time_)
    format = format.lower()
    # 1) Return time in seconds since epoc
    if 'epoch' in format:
        return time_
    dt = datetime.fromtimestamp(time_)
    parts = []
    for part, name in [(dt.year, 'year'), (dt.month, 'month'), (dt.day, 'day'),
                       (dt.hour, 'hour'), (dt.minute, 'min'), (dt.second, 'sec')]:
        if name in format:
            parts.append(f'{part:02}')
    # 2) Return time as timestamp
    if not parts:
        return dt.isoformat(' ', timespec='seconds')
    # Return requested parts of the time
    elif len(parts) == 1:
        return parts[0]
    else:
        return parts

parse_timestamp

parse_timestamp(timestamp: str | datetime) -> datetime

Parse timestamp in ISO 8601-like formats into a datetime.

Months, days, hours, minutes and seconds must use two digits and year must use four. Microseconds can use up to six digits. All time parts can be omitted.

Separators '-', '_', ' ', 'T', ':' and '.' between date and time components. Separators can also be omitted altogether.

Examples::

1
2
3
4
2023-09-08T14:34:42.123456
2023-09-08 14:34:42.123
20230908 143442
2023_09_08

This is similar to datetime.fromisoformat, but a little less strict. The standard function is recommended if the input format is known to be accepted.

If the input is a datetime, it is returned as-is.

New in Robot Framework 7.0.

Source code in src/robot/utils/robottime.py
def parse_timestamp(timestamp: 'str|datetime') -> datetime:
    """Parse timestamp in ISO 8601-like formats into a ``datetime``.

    Months, days, hours, minutes and seconds must use two digits and
    year must use four. Microseconds can use up to six digits. All time
    parts can be omitted.

    Separators '-', '_', ' ', 'T', ':' and '.' between date and time components.
    Separators can also be omitted altogether.

    Examples::

        2023-09-08T14:34:42.123456
        2023-09-08 14:34:42.123
        20230908 143442
        2023_09_08

    This is similar to ``datetime.fromisoformat``, but a little less strict.
    The standard function is recommended if the input format is known to be
    accepted.

    If the input is a ``datetime``, it is returned as-is.

    New in Robot Framework 7.0.
    """
    if isinstance(timestamp, datetime):
        return timestamp
    try:
        return datetime.fromisoformat(timestamp)
    except ValueError:
        pass
    orig = timestamp
    for sep in ('-', '_', ' ', 'T', ':', '.'):
        if sep in timestamp:
            timestamp = timestamp.replace(sep, '')
    timestamp = timestamp.ljust(20, '0')
    try:
        return datetime(int(timestamp[0:4]), int(timestamp[4:6]), int(timestamp[6:8]),
                        int(timestamp[8:10]), int(timestamp[10:12]), int(timestamp[12:14]),
                        int(timestamp[14:20]))
    except ValueError:
        raise ValueError(f"Invalid timestamp '{orig}'.")

parse_time

parse_time(timestr)

Parses the time string and returns its value as seconds since epoch.

Time can be given in five different formats:

1) Numbers are interpreted as time since epoch directly. It is possible to use also ints and floats, not only strings containing numbers. 2) Valid timestamp ('YYYY-MM-DD hh🇲🇲ss' and 'YYYYMMDD hhmmss'). 3) 'NOW' (case-insensitive) is the current local time. 4) 'UTC' (case-insensitive) is the current time in UTC. 5) Format 'NOW - 1 day' or 'UTC + 1 hour 30 min' is the current local/UTC time plus/minus the time specified with the time string.

Seconds are rounded down to avoid getting times in the future.

Source code in src/robot/utils/robottime.py
def parse_time(timestr):
    """Parses the time string and returns its value as seconds since epoch.

    Time can be given in five different formats:

    1) Numbers are interpreted as time since epoch directly. It is possible to
       use also ints and floats, not only strings containing numbers.
    2) Valid timestamp ('YYYY-MM-DD hh:mm:ss' and 'YYYYMMDD hhmmss').
    3) 'NOW' (case-insensitive) is the current local time.
    4) 'UTC' (case-insensitive) is the current time in UTC.
    5) Format 'NOW - 1 day' or 'UTC + 1 hour 30 min' is the current local/UTC
       time plus/minus the time specified with the time string.

    Seconds are rounded down to avoid getting times in the future.
    """
    for method in [_parse_time_epoch,
                   _parse_time_timestamp,
                   _parse_time_now_and_utc]:
        seconds = method(timestr)
        if seconds is not None:
            return int(seconds)
    raise ValueError("Invalid time format '%s'." % timestr)

get_timestamp

1
2
3
get_timestamp(
    daysep="", daytimesep=" ", timesep=":", millissep="."
)

Deprecated in Robot Framework 7.0. Will be removed in Robot Framework 8.0.

Source code in src/robot/utils/robottime.py
def get_timestamp(daysep='', daytimesep=' ', timesep=':', millissep='.'):
    """Deprecated in Robot Framework 7.0. Will be removed in Robot Framework 8.0."""
    warnings.warn("'robot.utils.get_timestamp' is deprecated and will be "
                  "removed in Robot Framework 8.0.")
    dt = datetime.now()
    parts = [str(dt.year), daysep, f'{dt.month:02}', daysep, f'{dt.day:02}', daytimesep,
             f'{dt.hour:02}', timesep, f'{dt.minute:02}', timesep, f'{dt.second:02}']
    if millissep:
        # Make sure milliseconds is < 1000. Good enough for a deprecated function.
        millis = min(round(dt.microsecond, -3) // 1000, 999)
        parts.extend([millissep, f'{millis:03}'])
    return ''.join(parts)

timestamp_to_secs

timestamp_to_secs(timestamp, seps=None)

Deprecated in Robot Framework 7.0. Will be removed in Robot Framework 8.0.

Source code in src/robot/utils/robottime.py
def timestamp_to_secs(timestamp, seps=None):
    """Deprecated in Robot Framework 7.0. Will be removed in Robot Framework 8.0."""
    warnings.warn("'robot.utils.timestamp_to_secs' is deprecated and will be "
                  "removed in Robot Framework 8.0. User 'parse_timestamp' instead.")
    try:
        secs = _timestamp_to_millis(timestamp, seps) / 1000.0
    except (ValueError, OverflowError):
        raise ValueError("Invalid timestamp '%s'." % timestamp)
    else:
        return round(secs, 3)

secs_to_timestamp

secs_to_timestamp(secs, seps=None, millis=False)

Deprecated in Robot Framework 7.0. Will be removed in Robot Framework 8.0.

Source code in src/robot/utils/robottime.py
def secs_to_timestamp(secs, seps=None, millis=False):
    """Deprecated in Robot Framework 7.0. Will be removed in Robot Framework 8.0."""
    warnings.warn("'robot.utils.secs_to_timestamp' is deprecated and will be "
                  "removed in Robot Framework 8.0.")
    if not seps:
        seps = ('', ' ', ':', '.' if millis else None)
    ttuple = time.localtime(secs)[:6]
    if millis:
        millis = (secs - int(secs)) * 1000
        ttuple = ttuple + (round(millis),)
    return format_time(ttuple, *seps)

get_elapsed_time

get_elapsed_time(start_time, end_time)

Deprecated in Robot Framework 7.0. Will be removed in Robot Framework 8.0.

Source code in src/robot/utils/robottime.py
def get_elapsed_time(start_time, end_time):
    """Deprecated in Robot Framework 7.0. Will be removed in Robot Framework 8.0."""
    warnings.warn("'robot.utils.get_elapsed_time' is deprecated and will be "
                  "removed in Robot Framework 8.0.")
    if start_time == end_time or not (start_time and end_time):
        return 0
    if start_time[:-4] == end_time[:-4]:
        return int(end_time[-3:]) - int(start_time[-3:])
    start_millis = _timestamp_to_millis(start_time)
    end_millis = _timestamp_to_millis(end_time)
    return end_millis - start_millis

elapsed_time_to_string

1
2
3
4
5
elapsed_time_to_string(
    elapsed: int | float | timedelta,
    include_millis: bool = True,
    seconds: bool = False,
)

Converts elapsed time to format 'hh🇲🇲ss.mil'.

Elapsed time as an integer or as a float is currently considered to be milliseconds, but that will be changed to seconds in Robot Framework 8.0. Use seconds=True to change the behavior already now and to avoid the deprecation warning. An alternative is giving the elapsed time as a timedelta.

If include_millis is True, '.mil' part is omitted.

Support for giving the elapsed time as a timedelta and the seconds argument are new in Robot Framework 7.0.

Source code in src/robot/utils/robottime.py
def elapsed_time_to_string(elapsed: 'int|float|timedelta',
                           include_millis: bool = True,
                           seconds: bool = False):
    """Converts elapsed time to format 'hh:mm:ss.mil'.

    Elapsed time as an integer or as a float is currently considered to be
    milliseconds, but that will be changed to seconds in Robot Framework 8.0.
    Use ``seconds=True`` to change the behavior already now and to avoid the
    deprecation warning. An alternative is giving the elapsed time as
    a ``timedelta``.

    If `include_millis` is True, '.mil' part is omitted.

    Support for giving the elapsed time as a ``timedelta`` and the ``seconds``
    argument are new in Robot Framework 7.0.
    """
    # TODO: Change the default input to seconds in RF 8.0.
    if isinstance(elapsed, timedelta):
        elapsed = elapsed.total_seconds()
    elif not seconds:
        elapsed /= 1000
        warnings.warn("'robot.utils.elapsed_time_to_string' currently accepts "
                      "input as milliseconds, but that will be changed to seconds "
                      "in Robot Framework 8.0. Use 'seconds=True' to change the "
                      "behavior already now and to avoid this warning. Alternatively "
                      "pass the elapsed time as a 'timedelta'.")
    prefix = ''
    if elapsed < 0:
        prefix = '-'
        elapsed = abs(elapsed)
    if include_millis:
        return prefix + _elapsed_time_to_string_with_millis(elapsed)
    return prefix + _elapsed_time_to_string_without_millis(elapsed)