How to format or print a difference in two DateTime objects

I want to print the following object, which is a difference between two DateTimes

datetime_diff = datetime2 - datetime1

The type of datetime_diff appears to be Milliseconds. That means it can be printed, but produces the following output which is not human readable

86398979 milliseconds

Sorry for asking such a basic question, but I cannot figure out how to format this in a more readable way.

Something like HH:MM:SS would be ideal.

Managed to figure this out…

datetime1 = DateTime(2024, 10, 24, 9, 0, 0)
datetime2 = DateTime(2024, 10, 24, 9, 30, 0)
datetime_diff = datetime2 - datetime1
ms = Millisecond(datetime_diff) # btw: it is already of type Millisecond
time  = Dates.Time(canonicalize(Dates.CompoundPeriod(ms)).periods...)
datetime_diff_str::String = Dates.format(time, "HH:MM:SS")
println("$(datetime_diff_str)")

However, it’s not great and I wish there was a more direct way to do such a thing. I would like to contribute something to the Dates library in Julia. I will put it on my list of things to do, and hopefully I will have some time to get around to it…

I’ve also found some alternative approaches which may be useful to some.

julia> using Dates

julia> ms = Millisecond(12345678)
12345678 milliseconds

julia> Dates.value(ms)
12345678

julia> typeof(Dates.value(ms))
Int64

julia> i = Dates.value(ms)
12345678

# get number of seconds, minutes, hours etc
# by performing truncating division on the integer value
# formed from the number of milliseconds and then
# converting to the correct explicit type
# in other words:
# 1. get Milliseconds object
# 2. convert to integer type
# 3. truncating division
# 4. create Second/Minute/Hour type from integer value
# this is a "unitless" approach
julia> Second(div(i, 1000))
12345 seconds

julia> Minute(div(i, 1000 * 60))
205 minutes
# alternatively you can do it in a way which maintains the units
julia> Millisecond(12000) / Millisecond(1000)
12.0

julia> Millisecond(12000000) / Millisecond(1000 * 60)
200.0

julia> Millisecond(12000000) / Millisecond(1000 * 60 * 60)
3.3333333333333335

julia>

Aha - and you can go further:

julia> Millisecond(12345678) / Second(1)
12345.678

julia> Millisecond(12345678) / Hour(1)
3.429355

All this code can be boiled down to:

t = Dates.Time(canonicalize(datetime_diff))
println("$t")

This was one of my earlier approaches, but I found that it didn’t work.

julia> dt1 = DateTime(2024, 10, 22, 9, 30)
2024-10-22T09:30:00

julia> dt2 = DateTime(2024, 10, 22, 10, 1)
2024-10-22T10:01:00

julia> Dates.Time(canonicalize(dt2 - dt1))
ERROR: MethodError: no method matching Int64(::Dates.CompoundPeriod)
The type `Int64` exists, but no method is defined for this combination of argument types when trying to construct it.

It will work if you load, in addition to Dates.jl, the package CompoundPeriods.jl.

Ok thank you, I will suggest my organization add that.