How to convert Milliseconds to Int64?

The following is not working:

julia> diff=Dates.Millisecond(55)
55 milliseconds

julia> convert(Int64, diff)
ERROR: MethodError: Cannot `convert` an object of type Millisecond to an object of type Int64
Closest candidates are:
  convert(::Type{T}, ::Gray24) where T<:Real at ~/.julia/packages/ColorTypes/1dGw6/src/conversions.jl:114
  convert(::Type{T}, ::Gray) where T<:Real at ~/.julia/packages/ColorTypes/1dGw6/src/conversions.jl:113
  convert(::Type{T}, ::Base.TwicePrecision) where T<:Number at ~/packages/julias/julia-1.7/share/julia/base/twiceprecision.jl:262
  ...
Stacktrace:
 [1] top-level scope
   @ REPL[19]:1

julia> 

How can I make this work?

You can access the value field of any TimePeriod type which should already be an Int64

2 Likes
julia> diff = Dates.Millisecond(55)
55 milliseconds

julia> Dates.value(diff)
55

julia> typeof(Dates.value(diff))
Int64
1 Like

A better error message when trying to use convert would be nice, though…

1 Like

Maybe a PR for better documentation? I did a help in the REPL for Date and DateTime and none of the examples indicated how to extract the values from the representation.

Perhaps define Base.convert(Int, x::Period) = value(x) inside Dates.
That way there is no need to export value, and people who see convert generally know there is some type&value transformation happening.

using Dates

Base.convert(::Type{Int64}, x::Period) = Dates.value(x)
Base.convert(::Type{Integer}, x::Period) = Dates.value(x)
2 Likes

Is there any updates on this (Dec 2024). The current solution works fine, but I do agree that a better error message and/or better documentation would help tremendously.

1 Like

A better way to get the same result might be through the Uniful package. The Unitful package is in general good to have in any real-world data setting, so there is mostly upside. Specifically:

julia> using Unitful

julia> diff = Dates.Millisecond(55)
55 milliseconds

julia> ustrip(diff)
55

julia> ustrip(diff) |> typeof
Int64

ustrip removes the unit part of any uniful quantity and leaves a scalar.