2020 / 08 / 15
Parse Twitter's date format with Elixir

How to parse something like Sun Aug 15 14:15:50 +0000 2021?

programming
elixir

Twitter’s API date format

If you are using Twitter’s API you’ve probably come across their particular way of formatting dates on user’s tweets:

created_at: "Sun Aug 15 14:15:50 +0000 2021",

Let’s see how we would parse that into something like this:

~U[2021-08-15 14:15:50Z]

Timex

Let’s use Timex for parsing.
Add this to you project dependencies:

  # ...
  defp deps do
    [
      {:timex, "~> 3.7"}
      # ...

Parse the date string

Let’s use the strftime date formatting language:

twitter_date = "Sun Aug 15 14:15:50 +0000 2021"

twitter_date
|> Timex.parse!("%a %b %d %H:%M:%S %z %Y", :strftime)
# ~U[2021-08-15 14:15:50Z]

We can use Timex own date formatting language too:

twitter_date = "Sun Aug 15 14:15:50 +0000 2021"

twitter_date
|> Timex.parse!("{WDshort} {Mshort} {D} {h24}:{m}:{s} {Z} {YYYY}")
# ~U[2021-08-15 14:15:50Z]

Alternatively you can skip parsing the timezone and thus get a naive datetime —with no timezone info— where you could do an extra step to convert it from NaiveDateTime to DateTime:

twitter_date = "Sun Aug 15 14:15:50 +0000 2021"

twitter_date
|> Timex.parse!("%a %b %d %H:%M:%S +0000 %Y", :strftime)
# ~N[2021-08-15 14:15:50] # no timezone information!
|> DateTime.from_naive!("Etc/UTC")
# ~U[2021-08-15 14:15:50Z]

References