Search code examples
pythonargparsedurationtimedelta

Python command parameter indicating time delta


I need to specify a parameter to a python script indicating time back from now. For example 1d is 1 day from now, 2h is 2 hours from now, 2d3h is 2 days, 3 hours from now. Similar to the journalctl --vacuum-time format (reference).

For example, this script will collect the data between now and 2 days and 3 hours in the past:

collect_data_script.py --start=2d3h

Is there some standard way to handle this parameter and a package that can process this time format? Or I will have to write it from scratch?


Solution

  • The ISO 8601 duration format like 2DT3H for "2 days (time designator) 3 hours" can be parsed using module isodate from Gerhard Weiss:

    implements ISO 8601 date, time and duration parsing. The implementation follows ISO8601:2004 standard

    parse_duration: parses an ISO 8601 duration string into a timedelta or Duration object.

    Example:

    import isodate
    
    isodate.parse_duration('p2d3h'.upper())  # prefix with 'p' for period and to uppercase
    # will raise ValueError because ISO 8601 time designator 'T' missing
    
    timedelta = isodate.parse_duration('p2dt3h'.upper())  # insert 'T' to work
    # datetime.timedelta(2, 10800)
    print(timedelta)
    # 2 days, 3:00:00
    

    Similar modules

    • arrow: offers a sensible and human-friendly approach to creating, manipulating, formatting and converting dates, times and timestamps.
    • duration: python time duration conversion module
    • iso8601: Simple module to parse ISO 8601 dates

    See also: