Adding an hour to datetime in Julia?

Viewed 311

Say I have a datetime and I want to add an arbitrary time period to that datetime and get a new datetime. For example, I want to find the date and time after 333 hours after new year's eve.

Two issues arise:

  1. I can't actually create an Time more than 23hours
  2. If I do create a ::Time, I can't add it to a ::DateTime

My question basically is how do you do add Times together?

Code

julia> dt = DateTime(2021,1)
2021-01-01T00:00:00

julia> t = Time(333)
ERROR: ArgumentError: Hour: 333 out of range (0:23)

julia> t = Time(1)
01:00:00

julia> dt + t
ERROR: MethodError: no method matching +(::DateTime, ::Time)
Closest candidates are:
  +(::Any, ::Any, ::Any, ::Any...) at operators.jl:560
1 Answers

You shouldn't be adding Times together, as these are instances in time. You want to be adding Periods to your Time to figure out what time it is after the period has elapsed:

julia> using Dates

julia> dt = DateTime(2021,1)
2021-01-01T00:00:00

julia> dt + Hour(333)
2021-01-14T21:00:00

julia> Hour <: Period
true

julia> Time <: Period
false
Related