Is there a way to make custom date formats in Julia?

Viewed 108

I would like to be able to convert

"Tue Sep 01 00:00:26 +00:00 2020"

into a date type in Julia using the built in Date function. I only need the year, month, and date.

2 Answers

This is tricky because you have a time zone here hence you need to use TimeZones.jl

using TimeZones, Dates
df = Dates.DateFormat("e u d H:M:S z y");
d = ZonedDateTime("Tue Sep 01 00:00:26 +00:00 2020", df)

Let se what we got:

julia> d = ZonedDateTime("Tue Sep 01 00:00:26 +00:00 2020", df)
2020-09-01T00:00:26+00:00

julia> Date(d)
2020-09-01

For more try typying ?DateFormat in the console - you will see the docs.

  Code     Matches   Comment
  –––––––– ––––––––– ––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
  y        1996, 96  Returns year of 1996, 0096
  Y        1996, 96  Returns year of 1996, 0096. Equivalent to y
  m        1, 01     Matches 1 or 2-digit months
  u        Jan       Matches abbreviated months according to the locale keyword
  U        January   Matches full month names according to the locale keyword
  d        1, 01     Matches 1 or 2-digit days
  H        00        Matches hours (24-hour clock)
  I        00        For outputting hours with 12-hour clock
  M        00        Matches minutes
  S        00        Matches seconds
  s        .500      Matches milliseconds
  e        Mon, Tues Matches abbreviated days of the week
  E        Monday    Matches full name days of the week
  p        AM        Matches AM/PM (case-insensitive)
  yyyymmdd 19960101  Matches fixed-width year, month, and day

To parse dates you need the Dates.jl standard library. To parse this particular format though, I think you additionally need the TimeZones.jl package:

using Dates
using TimeZones # gives the `z` for the format below
fmt = dateformat"e u d H:M:S z y" # the format of your string
d = Date("Tue Sep 01 00:00:26 +00:00 2020", fmt)

Then you can simply look at d's values for example with:

julia> d
2020-09-01

julia> year(d)
2020

julia> month(d)
9

julia> day(d)
1
Related