stefanchrobot
Inverse of DateTime.truncate?
Is there an inverse of DateTime.truncate? I have a DB column with :utc_datetime_usec type and I’m putting data coming from external system that has only precision up to a second.
I’m doing %{datetime | microsecond: {0, 6}} but maybe there’s a better way?
Should this be handled by Ecto internally? Seems like it’s failing on purpose.
Most Liked
eksperimental
from the DateTime docs:
Developers should avoid creating the
DateTimestruct directly and instead rely on the functions provided by this module as well as the ones in third-party calendar libraries.
stefanchrobot
Here’s the helper that I came up with. Only covers the use case I need, doctests included:
@doc """
Ensures that the given `DateTime` has the specified precision.
iex> ensure_precision(~U[2022-01-01 10:00:00Z], :microsecond)
~U[2022-01-01 10:00:00.000000Z]
iex> datetime = ~U[2022-01-01 10:00:00.123Z]
iex> DateTime.compare(datetime, ensure_precision(datetime, :microsecond))
:eq
"""
def ensure_precision(%DateTime{microsecond: {_, 6}} = datetime, :microsecond) do
datetime
end
def ensure_precision(%DateTime{microsecond: {value, _precision}} = datetime, :microsecond) do
%{datetime | microsecond: {value, 6}}
end
josevalim
DateTime.add(datetime, value, :microsecond)
Edit: ignore me, this does not change the precision of the DateTime but perhaps it should.
stefanchrobot
Doesn’t seem to work for me on Elixir 1.10:
iex> DateTime.utc_now() |> DateTime.truncate(:second) |> DateTime.convert!(Calendar.ISO) |> Map.get(:microsecond)
{0, 0}
eksperimental
I was wrong there. I wasn’t able to find anything.
Sounds like a set of extend/2 functions which take the same arguments as truncate/2 could be helpful.







