How can I convert a CompoundPeriod type object to Period type in Julia?

Using Dates module in Julia I am able to transform a Period type object (Hour, Minute, Second, Day etc.) to another Period type as below:

using Dates

julia> convert(Day, Hour(96))
4 days

julia> convert(Second, Hour(20))
72000 seconds

But if I try to convert any CompoundPeriod type object (Hour(2) + Minute(20), Week(3) + Day(5) etc.), it throws an error as below:

julia> convert(Second, Hour(3) + Minute(12))
ERROR: MethodError: Cannot `convert` an object of type Dates.CompoundPeriod to an object of type Second

Here, 3 hours + 12 minutes = 11520 seconds
Is there a Julia function to find the number of seconds (11520 seconds) in this case?
How can I convert a CompoundPeriod type object to Period type in Julia?

I don’t think there is a nice way to do this right now (but it would be good to add it). You can use Dates.tons or Dates.toms to convert a CompoundPeriod to a number in nanoseconds or milliseconds, but it will be a floating-point number, so you might lose some precision. For example, you could do

julia> c = Hour(3) + Minute(12)
3 hours, 12 minutes

julia> convert(Second, Millisecond(Dates.toms(c)))
11520 seconds

Another way, which does not use floating-point numbers, is the following:

julia> c = Hour(3) + Minute(12)
3 hours, 12 minutes

julia> sum(Second, c.periods)
11520 seconds

I have made a PR to enable conversion of CompoundPeriods to Periods.


Don’t know, if this is a good idea. From the docs:

help?> Dates.CompoundPeriod

  A CompoundPeriod is useful for expressing time periods that are not a fixed multiple of smaller periods. For
  example, "a year and a day" is not a fixed number of days, but can be expressed using a CompoundPeriod.

From this definition it seems clear, why there isn’t such a thing.
Of course, one can argue, that it should be available and do the conversion for those CompoundPeriods, where it is uniquely possible, like for hours+minutes to seconds.
Should it raise an error/exception for year+month e.g. into days?

I didn’t look into your PR, so perhaps you have already thought of all this issues.

1 Like

The conversion only works for CompoundPeriods for which all contained Periods can be converted. Otherwise, it throws a MethodError.

1 Like


Thank you @sostock . This is the best way so far :slight_smile:


using Dates, CompoundPeriods
t = Hour(3) + Minute(12)
Seconds(t)    # 11520 seconds
1 Like