Cannot convert Time to Time

Any idea what`s happening?

julia> s = "18:59:00"
"18:59:00"

julia> t0 = Time(s)
18:59:00

julia> t = Time(t0)
ERROR: MethodError: no method matching Int64(::Time)
The type `Int64` exists, but no method is defined for this combination of argument types when trying to construct it.

For comparison, no problems like this with Date or DateTime:

julia> sd = "2025-05-15T18:59:00"
"2025-05-15T18:59:00"

julia> d0 = DateTime(sd)
2025-05-15T18:59:00

julia> d = DateTime(d0)
2025-05-15T18:59:00

The background: I’ve array of mixed DateTime / Time and wanted to strip the Date part. Sure, there are easy workarounds… after being driven crazy by the error

1 Like

Shorter:

julia> Date(Date(0))
0000-01-01

julia> DateTime(DateTime(0))
0000-01-01T00:00:00

julia> Time(Time(0))
ERROR: MethodError: no method matching Int64(::Time)

That constructor just isn’t defined so it falls back to the generic single-arg Time(h) constructor which calls Time(Int64(h)...) hence the error.

Seems like that might be reasonable to add, check if there’s an issue on the Dates repo and open one if there isn’t?

2 Likes

would do it

It’s worth reminding that the API for conversion is convert, and when the target type is already met, it falls back to returning the input like identity. Constructors however are intended for instantiation, so when the input matches the target type, it tends to be cloned. A rough rule for instantiation returning the input is when cloning an immutable type would result in the same instance anyway, or if the API is immutable so we shouldn’t rely on the mutable type’s identity e.g. BigInt. For example, x = 3; Integer(x) === x returns true. For a counterexample, x = [3]; Vector(x) === x returns false. There are also cases where instantiation wouldn’t clone; for example, Ref(Ref(1)) adds a 2nd layer of reference.

Time is immutable so Time(x::Time) = x is reasonable, but it’s best to use convert when your program strictly needs to convert (which it may not).

1 Like