tlnagy
tlnagy

Reputation: 3474

Round Julia's Millisecond type to nearest Second or Minute

I would like to calculate the difference between a pair of DateTimes that is rounded to the nearest second or minute.

initial = now()
println(typeof(initial))
sleep(12)
final = now()
difference = final - initial
println(typeof(difference))

gives

DateTime
Base.Dates.Millisecond

The latter type is pretty difficult to use since almost all convenience types are for DateTimes. What is the recommend way to convert difference to seconds or fractional minutes? Is this possible without dropping down to integers? I would prefer to avoid that since it is more error prone.

Upvotes: 3

Views: 2288

Answers (1)

TigerhawkT3
TigerhawkT3

Reputation: 49330

Since difference represents a duration between dates rather than a particular time, it makes sense for it to just be a duration in milliseconds. Additionally, DateTime and Base.Dates.Millisecond objects are internally represented with an Int64, so everything's already an integer.

julia> moment = now()
2016-12-22T22:54:57.393

julia> dump(moment)
DateTime
  instant: Base.Dates.UTInstant{Base.Dates.Millisecond}
    periods: Base.Dates.Millisecond
      value: Int64 63618130497393

julia> dump(now()-moment)
Base.Dates.Millisecond
  value: Int64 29820

Divide the value in milliseconds by 1000 to get seconds, or by 60,000 to get minutes. Use round() to round to the nearest second or minute.

julia> d = (now() - moment).value/60_000
3.9330833333333333

julia> e = round(d)
4.0

Then multiply by 1000 or 60,000 and feed it back into Dates.Millisecond to turn the rounded figure back into the appropriate object:

julia> Dates.Millisecond(60_000e)
240000 milliseconds

Rounding a Date or DateTime object to a given time interval is much simpler, as you can just use round() according to the documentation and it will dispatch to a relevant method:

julia> floor(Date(1985, 8, 16), Dates.Month)
1985-08-01

julia> ceil(DateTime(2013, 2, 13, 0, 31, 20), Dates.Minute(15))
2013-02-13T00:45:00

julia> round(DateTime(2016, 8, 6, 20, 15), Dates.Day)
2016-08-07T00:00:00

Upvotes: 6

Related Questions