Elixir DateTime Conversion

I am writing a test case, the data returns contain a DateTime field :

 modified_at: Timex.now()

which has the value like this:

modified_at: ~U[2019-07-25 08:22:36.000000Z]

But Jason encoder encodes this value to a string:


In the test, when I assert the value ofmodified_at, it gives me wrong microseconds value.

assert  modified_at == DateTime.to_iso8601(~U[2019-07-25 08:22:36.000000Z]

It gives me this DateTime


It does not round off the microseconds value, and I can’t understand why it’s showing such behavior.

Any help will be much appreciated.


Are you using ecto here? If so, which type do you use?

Yes I using ecto sql and the field type of modified_at is :utc_datetime_usec. if thats what you are asking.

Note, Timex.now() has microsecond precision:

iex> Timex.now()
~U[2019-07-25 11:08:41.557083Z]

and you’re saying you have (...).000000Z so something is automatically truncating it. Could you show a way to reproduce this issue? Are you using Changeset.cast or Changeset.change to set modified_at?

1 Like