Formating Dates.CompoundPeriod

I have variable of type Dates.CompoundPeriod
I need to change it to String in format HH:MM:SS (value will never exceed 1 hour)

julia> x = Dates.CompoundPeriod(Dates.Hour(12), Dates.Minute(13))
12 hours, 13 minutes

julia> Dates.format(x, dateformat"HH:MM:SS")
ERROR: MethodError: no method matching format(::Dates.CompoundPeriod, ::DateFormat{Symbol("HH:MM:SS"),Tuple{Dates.DatePart{'H'},Dates.Delim{Char,1},Dates.DatePart{'M'},Dates.Delim{Char,1},Dates.DatePart{'S'}}})
Closest candidates are:
  format(::TimeType, ::DateFormat) at julia\stdlib\v1.5\Dates\src\io.jl:535
  format(::TimeType, ::DateFormat, ::Any) at julia\stdlib\v1.5\Dates\src\io.jl:535
  format(::Any, ::Dates.DatePart{'s'}, ::Any) at julia\stdlib\v1.5\Dates\src\io.jl:203

Is there any standard way to do this? Or do I have to parse string as
n1 hours, n2 minutes, n3 seconds
?

Thank you.

2 Likes

You should parse/convert your CompoundPeriod into a Dates.Time type object. It has support for formatting.

So far, in Julia converting a CompoundPeriod type object to any other Period type or TimeType is not straightforward. @Laco_Kovac, you can notice another topic here.

@quinnj, I think you are trying to say something like this:

julia> using Dates

julia> x = Dates.CompoundPeriod(Dates.Hour(12), Dates.Minute(13))
12 hours, 13 minutes

julia> Dates.format(Dates.Time(x.periods[1], x.periods[2]), dateformat"HH:MM:SS")
"12:13:00"

Thank you!

Dates.format(Dates.Time(x.periods…), dateformat"HH:MM:SS")

That is the best solution for my issue, because x could contain any of the 3 (hours, minutes, seconds).

1 Like

What I don’t understand with either solution is will this work in general?

What happens if you have a CompoundPeriod which is Days(1) + Seconds(1).

Is this represented as a Tuple?

  • What is compound_period[1] ? Days(1)?
  • What is compound_period[2] ? Seconds(1)?

Then following on to the second quote -

  • Dates.Time(compound_period...) < would this behave correctly?

I’ve managed to answer some of my questions using the REPL.

Here are my findings.

Using the splay syntax appears to work in general. I guess Julia does something intelligent to match up keyword arguments. (I’m not super familiar with Julia yet.)

Here’s an example of something which works in general.

z = Dates.CompoundPeriod(Dates.Hour(12), Dates.Second(30), Dates.Minute(10), Dates.Millisecond(1))
12 hours, 10 minutes, 30 seconds, 1 millisecond

Dates.format(Dates.Time(z.periods...), "HH:MM:SS")
"12:10:30"

It will not work if the time duration exceeds 24 hours. For example, you cannot do this:

z = Dates.CompoundPeriod(Dates.Day(1))
Dates.format(Dates.Time(z.periods...), "HH:MM:SS") # will error