Time period conversion to seconds, for plotting

Meganecroposting here because of this problem I ran into while trying to format ticks on a logarithmic x-axis that represents time intervals.

using Dates

convert(Second, Week(100))
60480000 seconds

convert(Second, Month(3))
ERROR: MethodError: Cannot `convert` an object of type Month to an object of type Second

So much for compound periods and so forth.

The solution above will help me design a function to solve my problem, but also I’m looking into the Unitful.jl pacakge.

As usual with Date/Time stuff things are complicated.
A month does not have a constant number of seconds.
So, error. Can’t think of a way to fix this. Perhaps return an interval of possible answers.

Yes well good news! I read some docs, esp. the Unitful.jl docs by which I found out about the Dates FixedPeriod type. It makes sense, a month or year is not a fixed number of days/hours/sec etc.

help?> Dates.FixedPeriod

  Summary
  ≡≡≡≡≡≡≡

  Dates.FixedPeriod is of type Union.

  Union Composed of Types
  ≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡

    •  Day

    •  Hour

    •  Microsecond

    •  Millisecond

    •  Minute

    •  Nanosecond

    •  Second

So Dates types wont convert to Month/Year because of the indeterminate length, depending on the specific date. Unitful defines a year as exactly 365.25 days though, so the conversion works for year but not months.

Using Unitful

uconvert(u"s", 1*u"yr")
31557600 s

Good design by the Julia Team! I’ll just create a function to display units the way I like.

1 Like