有没有办法在Julia中制作自定义日期格式?

我希望能够转换

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

使用内置的 Date 函数在 Julia 中转换为日期类型。我只需要年、月和日。

回答

这很棘手,因为您在这里有一个时区,因此您需要使用 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)

让我们看看我们得到了什么:

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

如需更多信息,请尝试?DateFormat在控制台中输入 - 您将看到文档。

  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

  • Ha! You ninja'd me! 🙂
  • Yeah this is a crazy race 😉

回答

要解析日期,您需要 Dates.jl 标准库。不过,要解析这种特定格式,我认为您还需要 TimeZones.jl 包:

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)

然后,您可以简单地查看d的值,例如:

julia> d
2020-09-01

julia> year(d)
2020

julia> month(d)
9

julia> day(d)
1


以上是有没有办法在Julia中制作自定义日期格式?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>