Storing and parsing Dates.CompoundPeriod?

Hi,
In a small application I need to store and do simple arithmetics on durations (estimates and effort).
So far the best option I have found seem to be Dates.CompoundPeriod, which works fine for now, providing addition out of the box and division of my own implementation (umm a bit of local type piracy I guess…)
So far I get by with storing my data (tree) with JLD, but wanting to store the data in a database eg SQLite is not unreasonable here, which brings me to the question.
What is the best way of storing Dates.CompoundPeriod data, and in particular in a database?
String seems like the obvious choice as it is supported by any database, but then I have not found a supported way to parse a string back to a Dates.CompoundPeriod…
I did find https://discourse.julialang.org/t/parsing-string-to-dates-compoundperiod/25484/7 but that is not really about trying to parse a Dates.CompundPeriod in string representation back to the actual data type.
Or is there simply a more suitable way way to represent a duration than Dates.CompoundPeriod in Julia?

1 Like

Not sure if the approach below makes sense, but fwiw:

using Dates

# CompoundPeriod
cp1 = Hour(25) + Second(62) + Microsecond(10)

# Output as 2 strings
v1 = string.(Dates.value.(cp1.periods))
s1 = string.(typeof.(cp1.periods))

# Parse strings
cp2 = sum([eval(Meta.parse("$s($v)")) for (v,s) in zip(v1,s1)])

cp2 == cp1      # true

Not quite, as the string representation in the example is
"25 hours, 62 seconds, 10 microseconds"
and thus that is what needs to be parsed. Can’t directly get the “component” Periods from that.
But the Meta.parse stuff was helpful, should be possible to use a regexp and get essentially the same building blocks that you picked directly from cp1.periods. Thx!

OK.
One option without regexp:

using Dates

# CompoundPeriod
cp1 = Hour(25) + Second(62) + Microsecond(10)
str1 = string(cp1)

# Parse string
x = split.(split(str1, ','))
v1 = first.(x)
s1 = chop.(uppercasefirst.(last.(x)))
cp2 = sum([eval(Meta.parse("$s($v)")) for (v,s) in zip(v1,s1)])

cp2 == cp1      # true
1 Like

You could use the ISO 8601 duration format - though I don’t believe an existing parser for julia exists. So in that example it would be "PT25H62.000010". Postgres has a native datatype that can store this format too

Really neat!