0

Converting seconds to Hours:Minutes:Seconds has been answered a number of ways for Python here.

How would one do this in Julia?

Julia Learner
  • 2,754
  • 15
  • 35

2 Answers2

2

Method 1:

This code follows Brandon Rhodes answer in Python at the link in the original question. It answers the original question.

Advantage: Simplicity.

Disadvantage: For long simulation runs the output will not be formatted as nicely as the method given after this one.

using Printf

start = time()
sleep(65.129)  # 65.129 seconds
elapsed = time() - start

(minutes, seconds) = fldmod(elapsed, 60)
(hours, minutes) = fldmod(minutes, 60)

@printf("%02d:%02d:%0.2f", hours, minutes, seconds)

"""========== The expected output is ==========
00:01:5.16
"""

Method 2:

@crstnbr solves a similar problem with the canonacalize function. I do not see it in the Julia 1.0.0 documentation, but I found it in the Julia source as linked here.

It has the neat property of gracefully handling both short and long elapsed time periods.

Advantage: Provides a useful format for long elapsed times.

Disadvantage: Does not seem to be in the current Julia 1.0.0 documentation, may be hard to remember.

julia> start = now(); sleep(1.23); elapsed = now() - start;
julia> canonicalize(Dates.CompoundPeriod(elapsed))
1 second, 246 milliseconds

julia> canonicalize(Dates.CompoundPeriod(elapsed*1000000))
2 weeks, 10 hours, 6 minutes, 40 seconds

If you are doing long simulations, that might be helpful.

Julia Learner
  • 2,754
  • 15
  • 35
1

Not really what you asked for, but maybe still useful:

julia> using Dates

julia> start = now(); sleep(1.23); elapsed = now() - start;

julia> canonicalize(Dates.CompoundPeriod(elapsed))
1 second, 231 milliseconds

See https://discourse.julialang.org/t/conversion-and-formatting-of-dates-timeperiod/15063.

carstenbauer
  • 9,817
  • 1
  • 27
  • 40