Need to find datetime for a datetime plus a duration/period/timedelta

Suppose I have a period, defined by Time() and a datetime, DateTime().

My goal is to to get a new datetime:

using Dates
startTime = DateTime(2021,2,14,19,00)
duration  = Time(4,30)

endTime = startTime + duration

Above code returns:

ERROR: MethodError: no method matching +(::DateTime, ::Time)

How do I achieve getting the datetime for a datetime plus the duration / period / timedelta?

If any other approach reach my goal, it is more than welcome!

I cannot seem to find any lead, so I hope you, the incredible hive mind of Julia, can help me.

1 Like

Your duration is not a duration though, it is being interpreted as an actual time of day. If you want 4.5 hours added to start then you can do start+Minute(270) which adds 270 minutes (4.5 hours).

2 Likes

Aahh, great - thanks a lot!

Is there a convenience function for handling the duration more intuitively instead of total number of minutes? Which is doing something like the following?

function duration(h::Int64=0,m::Int64=0,s::Int64=0,ms::Int64=0,mus::Int64=0,ns::Int64=0)
    return (Hour(h) + Minute(m) + Second(s) + Millisecond(ms) + Microsecond(mus) + Nanosecond(ns))
end

Not that I know if but you can also just do start+Hour(4)+Minute(30)

1 Like

Dates.CompoundPeriod could work as well but if you have consistent duration types then use the original answer. It gives an answer much faster.

julia> @time Dates.CompoundPeriod(duration) + startTime
  0.000026 seconds (20 allocations: 496 bytes)
2021-02-14T23:30:00

julia> @time startTime + Hour(4) + Minute(30)
  0.000012 seconds (9 allocations: 288 bytes)
2021-02-14T23:30:00

julia> @time startTime + Minute(270)
  0.000004 seconds (1 allocation: 16 bytes)
2021-02-14T23:30:00
1 Like