Editor

Parse a Duration

#360 · Parsing · Advanced · 125 XP · about 25 min

Timers and calendar apps accept durations typed by people, such as "1h 30m", "2d4h", "90s" or "1 hour, 20 minutes and 5 seconds". Write parse_duration(text) that returns the length of the duration in seconds, or -1 if text is not a valid duration.

A duration is one or more parts. Each part is a whole number (digits only) followed by a unit, with or without spaces between them. These are the units, and upper and lower case letters are both fine:

  • days: d, day, days (86,400 seconds)
  • hours: h, hr, hrs, hour, hours (3,600 seconds)
  • minutes: m, min, mins, minute, minutes (60 seconds)
  • seconds: s, sec, secs, second, seconds (1 second)

The rest of the rules:

  • Between two parts there may be nothing ("2d4h"), spaces, a comma, the word and, or a comma and then and. Spaces may go anywhere around a comma. The word and needs a space after it, and a space before it unless it comes right after the comma.
  • Units go from larger to smaller, and each unit is used at most once.
  • Spaces at the start and the end are fine. Anything else makes the text invalid: any other character, a number without a unit, a unit without a number, a word that is not a unit, or a comma or and that is not between two parts.

Examples

parse_duration('1h 30m')    # returns 5400
parse_duration('2d4h')      # returns 187200
parse_duration('90s')       # returns 90
parse_duration('1 hour, 20 minutes and 5 seconds')  # returns 4805
parse_duration('30m 1h')    # returns -1

The last one is invalid because minutes come before hours.

Constraints

  • text has at most 200,000 characters, all ASCII, and its only whitespace is spaces.
  • Numbers have at most 30 digits.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.