1

I am wondering why I can't dump a DateTime with a precision less than 6? Why can't we just fill up with zeros?

Example

iex> {:ok, datetime, _} = DateTime.from_iso8601("1970-01-01T00:00:00Z")
{:ok, #DateTime<1970-01-01 00:00:00Z>, 0}

Expected

iex> Ecto.Type.dump(:utc_datetime_usec, datetime)
{:ok, #DateTime<1970-01-01 00:00:00.000000Z>}

Actual

iex> Ecto.Type.dump(:utc_datetime_usec, datetime)
** (ArgumentError) :utc_datetime_usec expects microsecond precision, got: #DateTime<1970-01-01 00:00:00Z>
    (ecto) lib/ecto/type.ex:1217: Ecto.Type.check_usec!/2
    (ecto) lib/ecto/type.ex:419: Ecto.Type.dump_utc_datetime_usec/1
Jan
  • 11
  • 1
  • What is your question? Why would you expect _Ecto_ to make a [possibly erroneous] guesses about your intent instead of explicitly telling “you are doing it wrong”? Please note, that the actual value, in this case, _does not have a `usec` defined_ which is absolutely not the same as _having it defined to be zeroes_. – Aleksei Matiushkin May 20 '19 at 11:57
  • 1
    Okay, got it :-) That's what I wanted to know! – Jan May 20 '19 at 12:11

1 Answers1

0

As the type name says, utc_datetime_usec does expect usec precision. So giving it anything with less precision will make it fail. You can use utc_datetime if you don't want to enforce microseconds.

José Valim
  • 50,409
  • 12
  • 130
  • 115
  • 1
    But why? If your are getting the `DateTime.from_iso8601/1`, depending on the original encoder, the trailing zeros could be truncated (from the same reason we have `0.1` and not `0.1000`). And there is no easy way (from standard library) to increase / guarantee precision when parsing to DateTime. Would you acceps `DateTime.upscale(dt, :microseconds)` in standard lib? – mpm Sep 23 '22 at 16:15