This doesn’t work for periods longer than a day:
julia> using Dates
julia> myformat(sec::Dates.Second, fmt::AbstractString) = Dates.Time(Dates.canonicalize(sec).periods...);
julia> myformat(Second(500), "HH:MM:SS")
00:08:20
julia> myformat(Second(5000), "HH:MM:SS")
01:23:20
julia> myformat(Second(50000), "HH:MM:SS")
13:53:20
julia> myformat(Second(500000), "HH:MM:SS")
ERROR: MethodError: no method matching Int64(::Day)
The type `Int64` exists, but no method is defined for this combination of argument types when trying to construct it.
Closest candidates are:
Int64(::Float64)
@ Base float.jl:919
Int64(::Float32)
@ Base float.jl:919
Int64(::Float16)
@ Base float.jl:919
...
Stacktrace:
[1] Time(h::Day, mi::Hour, s::Minute, ms::Second, us::Int64, ns::Int64, ampm::Dates.AMPM)
@ Dates ~/.julia/juliaup/julia-1.12.4+0.aarch64.apple.darwin14/share/julia/stdlib/v1.12/Dates/src/types.jl:423
[2] myformat(sec::Second, fmt::String)
@ Main ./REPL[2]:1
[3] top-level scope
@ REPL[6]:1
Meanwhile Python has no problem printing large time periods:
>>> from datetime import timedelta
>>> str(timedelta(seconds=800000000.9))
'9259 days, 6:13:20.900000'
(However, “9259 days” makes no sense; at this point it should be split into weeks, months and years)
Using nanoseconds doesn’t work either:
julia> using Dates
julia> begin
myformat(period::Dates.TimePeriod, fmt::AbstractString) =
Dates.Time(Dates.canonicalize(period).periods...)
myformat(sec::Real, fmt::AbstractString) =
myformat(Dates.Nanosecond(round(Int, sec * 1e9)), fmt)
end;
julia> myformat(100306.25350200786, "HH:MM:SS")
ERROR: MethodError: no method matching Time(::Day, ::Hour, ::Minute, ::Second, ::Millisecond, ::Microsecond, ::Nanosecond)
The type `Time` exists, but no method is defined for this combination of argument types when trying to construct it.
Closest candidates are:
Time(::TimePeriod, ::TimePeriod...)
@ Dates ~/.julia/juliaup/julia-1.12.4+0.aarch64.apple.darwin14/share/julia/stdlib/v1.12/Dates/src/types.jl:378
Time(::Any, ::Any, ::Any, ::Any, ::Any, ::Any)
@ Dates ~/.julia/juliaup/julia-1.12.4+0.aarch64.apple.darwin14/share/julia/stdlib/v1.12/Dates/src/types.jl:423
Time(::Any, ::Any, ::Any, ::Any, ::Any, ::Any, ::Dates.AMPM)
@ Dates ~/.julia/juliaup/julia-1.12.4+0.aarch64.apple.darwin14/share/julia/stdlib/v1.12/Dates/src/types.jl:423
...
Stacktrace:
[1] myformat
@ ./REPL[3]:2 [inlined]
[2] myformat(sec::Float64, fmt::String)
@ Main ./REPL[3]:4
[3] top-level scope
@ REPL[13]:1
Apparently Day is not a TimePeriod:
julia> Day <: TimePeriod
false
…which is why Time(period::TimePeriod, periods::TimePeriod...) is not called. Instead, Time(h, mi=0, s=0, ms=0, us=0, ns=0, ampm::AMPM=TWENTYFOURHOUR) is called.
If Day is not a TimePeriod, what is it, then??? Same for Week, Month, etc: are they not time periods?