user2138149
user2138149

Reputation: 17266

How to parse a "duration" type from a String in Julia?

The result of subtracting two DateTime objects in Julia is some kind of duration object.

Running this in the REPL, I find that the returned type is a "milliseconds" type, which I believe is Dates.Millisecond.

I am trying to write a configuration file which can be used to specify some duration values.

While DateTime values can be parsed from string, I am not sure how to parse a "duration" type, or even which "duration" type I should choose.

For context the duration values will typically be a number of hours and minutes. For example "9 hours and 30 minutes". (Although not with this exact string representation.) "09:30" or "9h30" would probably be more sensible string representations.

There are multiple types of "duration" in the Julia Dates package. The most frequent ones I have encountered are the Millisecond duration, Dates.Period and Dates.CompoundPeriod.

I am not sure what the most sensible approach would be. Requiring the user to enter a number of milliseconds is clearly not a very user-friendly solution. While I could parse an integer value and convert it to Millisecond, this doesn't seem like a very sensible approach.

Upvotes: -1

Views: 51

Answers (1)

BallpointBen
BallpointBen

Reputation: 13857

Ask for a time string formatted like HH:MM:SS, append it to a known date string, parse that into a DateTime, then subtract the original date. (Or just use regex, but this is more fun.)

julia> function parse_time(s)
           base_date = DateTime(2000)
           base_date_str = Dates.format(base_date, dateformat"yyyy-mm-dd")
           datetime_str = "$base_date_str $s"
       
           num_colons = count(':', s)
           datetime_fmt = if num_colons == 1
               dateformat"yyyy-mm-dd HH:MM"
           elseif num_colons == 2
               dateformat"yyyy-mm-dd HH:MM:SS"
           else
               error("unrecognized time format in $(s)")
           end
       
           datetime = DateTime(datetime_str, datetime_fmt)
           return datetime - base_date
       end
parse_time (generic function with 1 method)

julia> println(parse_time("1:23"))
4980000 milliseconds

julia> println(parse_time("12:34:56"))
45296000 milliseconds

Upvotes: 0

Related Questions