robinkwilson

robinkwilson

Best way to get all entries for one day, or date range, using Ecto.Query?

Hi! I spent a long time trying to figure out the best way to get all entries in a specific date range. So wanted to share my solution and see if there’s a better way.

Is this the best way to go about it? Set all NaiveDateTime’s time to 00:00:00.0000 for today and tomorrow, then get today >= and < tomorrow’s entries.

  @seconds_in_a_day 24 * 60 * 60
  def get_list_of_today_values(utc_date) do
    {:ok, time} = Time.new(0, 0, 0, 0)

    {:ok, today_date} = \
      utc_date \
      |> NaiveDateTime.to_date() \
      |> NaiveDateTime.new(time)

    next_day_date = today_date |> NaiveDateTime.add(@seconds_in_a_day, :second)

    from(ss in StorageStat, where: ss.measured_at >= ^today_date and ss.measured_at < ^next_day_date)
    |> Repo.all()
  end

Most Liked

Eiji

Eiji

If you want to return all entries from said date then how about simply converting PostgreSQL’s timestamp to date?

Here is an example script:

Mix.install([:ecto_sql, :postgrex])

defmodule Migration do
  use Ecto.Migration

  def change do
    create table("tests") do
      add(:timestamp, :naive_datetime)
    end
  end
end

defmodule Repo do
  use Ecto.Repo, adapter: Ecto.Adapters.Postgres, otp_app: :my_app
end

defmodule Test do
  use Ecto.Schema

  schema "tests" do
    field(:timestamp, :naive_datetime_usec)
  end
end

defmodule Example do
  alias Ecto.Query
  require Query

  def cleanup do
    Repo.stop()
  end

  def prepare do
    Application.put_env(:my_app, Repo,
      database: "example",
      password: "postgres",
      username: "postgres"
    )

    _ = Repo.__adapter__().storage_down(Repo.config())
    :ok = Repo.__adapter__().storage_up(Repo.config())
    {:ok, _} = Supervisor.start_link([Repo], strategy: :one_for_one)
    Ecto.Migrator.up(Repo, 0, Migration)
  end

  def sample do
    now = NaiveDateTime.utc_now()

    Test
    |> Query.from(as: :test)
    |> Query.where(
      [test: test],
      fragment("?::date = ?::date", test.timestamp, type(^now, :naive_datetime))
    )
    |> Query.select([test: test], test.timestamp)
    |> Repo.all()
    |> IO.inspect()
  end

  def seed do
    seconds_in_day = 24 * 60 * 60
    now = NaiveDateTime.utc_now()
    yesterday = NaiveDateTime.add(now, seconds_in_day * -1, :second)
    tomorrow = NaiveDateTime.add(now, seconds_in_day, :second)
    Repo.insert(%Test{timestamp: yesterday})
    Repo.insert(%Test{timestamp: now})
    Repo.insert(%Test{timestamp: tomorrow})
  end
end

Example.prepare()
Example.seed()
Example.sample()
Example.cleanup()

Where Next?

Popular in Questions Top

lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
Phillipp
Hey, I have a NanoPi-M3 and try to install Elixir on their Ubuntu image. I followed the Raspberry Pi installation instructions from the ...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
Codball
Mix format works fine if run from the cmd. I’ve followed this to facilitate the implementation into VSC which involves downloading an ext...
New
Mooodi
Given a string, how can I get access to its character by index? Enum.at("my_string", 2) doesn't work. Or rather, not char, but a substr...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New

Other popular topics Top

TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
New
peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; someth...
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

We're in Beta

About us Mission Statement