Cannot compare some time periods

Some periods of time, e.g. Millisecond vs Month, behave as incomparable:

using Dates
Millisecond(2) < Week(2)  # true
Millisecond(2) < Month(2)  # error

The reason for this error is unclear for me. Even the error trace (see below) says that there exists a corresponding isless method:

julia> Millisecond(2) < Month(2)
ERROR: MethodError: no method matching isless(::Millisecond, ::Month)
Closest candidates are:
  isless(::Union{Day, Hour, Microsecond, Millisecond, Minute, Nanosecond, Second, Week}, ::Union{Month, Year}) at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.0/Dates/src/periods.jl:464
  isless(::Period, ::Period) at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.0/Dates/src/periods.jl:71
  isless(::Missing, ::Any) at missing.jl:66
  ...
Stacktrace:
 [1] isless(::Millisecond, ::Month) at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.0/Dates/src/periods.jl:464
 [2] <(::Millisecond, ::Month) at ./operators.jl:260
 [3] top-level scope at none:0

versioninfo():


Julia Version 1.0.2
Commit d789231e99 (2018-11-08 20:11 UTC)
Platform Info:
  OS: Linux (x86_64-pc-linux-gnu)
  CPU: Intel(R) Xeon(R) CPU E5-1650 v4 @ 3.60GHz
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-6.0.0 (ORCJIT, broadwell)
Environment:
  JULIA_VERSION = 1.0.2
  JULIA_NUM_THREADS = 12

AFAIK <:FixedPeriods are only comparable to other fixed periods, see

https://github.com/JuliaLang/julia/pull/21378

Okay, and does this mean that the only way to see if a millisecond-based period is larger than e.g. half a year is to compare period > Week(26) (or using smaller units like days)?

Yes, the point is that you have to use a time period which actually has a fixed definition. A month is not a fixed period, nor is a year (it’s a calendar year not an astronomical year). It’s a terrible system, but some parts of it go back about 5000 years so I guess we’re stuck with it.

Depending on what you’re doing you might define some custom functions. In light of the above, it would probably make more sense to talk about periods like, for example 182 days rather than half a year.

1 Like

I see, it’s actually the same in python. Then the only thing still bothering me is that the error message is completely unintuitive - it says that there is no method isless(::Millisecond, ::Month), while this very traceback comes from isless(::Millisecond, ::Month) at .... It made me think that it’s a bug in method resolution or something like that.

The MethodError is indeed very confusing. Maybe a DomainError would be more useful.