Rounding DateTime


sorry for the basic question.

I want to round the time values of a time series to various periods, let’s say a 10-second-period, so that for example 10:23:47 becomes 10:23:40

I wanted to do this with the following code:

julia> dt = DateTime(2020, 03, 23, 07, 29, 37, 869)

julia> dtval = Dates.value(dt)

julia> dtval = dtval - (dtval % 10000)

But I don’t know how to construct a DateTime object from the Int64 representation. Can anyone help?

The docstring for round contains some clues that may be useful

  round(dt::TimeType, p::Period, [r::RoundingMode]) -> TimeType

  Return the Date or DateTime nearest to dt at resolution p. By default (RoundNearestTiesUp), ties (e.g., rounding
  9:30 to the nearest hour) will be rounded up.

  For convenience, p may be a type instead of a value: round(dt, Dates.Hour) is a shortcut for round(dt,

  julia> round(Date(1985, 8, 16), Dates.Month)
  julia> round(DateTime(2013, 2, 13, 0, 31, 20), Dates.Minute(15))
  julia> round(DateTime(2016, 8, 6, 12, 0, 0), Dates.Day)

  Valid rounding modes for round(::TimeType, ::Period, ::RoundingMode) are RoundNearestTiesUp (default), RoundDown
  (floor), and RoundUp (ceil).

  round(x::Period, precision::T, [r::RoundingMode]) where T <: Union{TimePeriod, Week, Day} -> T

  Round x to the nearest multiple of precision. If x and precision are different subtypes of Period, the return value
  will have the same type as precision. By default (RoundNearestTiesUp), ties (e.g., rounding 90 minutes to the
  nearest hour) will be rounded up.

  For convenience, precision may be a type instead of a value: round(x, Dates.Hour) is a shortcut for round(x,

  julia> round(Dates.Day(16), Dates.Week)
  2 weeks
  julia> round(Dates.Minute(44), Dates.Minute(15))
  45 minutes
  julia> round(Dates.Hour(36), Dates.Day)
  2 days

Wow, that’s much easier than I thought – I didn’t know the round() function yet.

1 Like

The REPL help mode has some nice search functionalities, e.g., asking for help on a string searches all docstrings for that string

help?> "round"

You can also call the function apropos directly.


I didn’t know this, is this new? And how is it different from apropos("round"), which returns lots more (in this case mostly unhelpful, I’d say…) hits?

They are equivalent, I only included the first two hits when I illustrated the usage :slight_smile:

1 Like