我在 Julia 中使用 DataFrame,想要过滤一些 Date 和 DateTime 列。为此,每当运行数据作业时,我都需要前一个月的最后一天。
例如,如果今天的日期是 Date("2021-07-21")
,我想获得 2021-06-30
。
我一直在 Redshift SQL 中执行此操作,如下所示:
select last_day(current_date - interval '1 month');
┌────────────┐
│ last_day │
├────────────┤
│ 2021-06-30 │
└────────────┘
答案 0 :(得分:4)
在我记得检查Julia standard library Dates之前,我发现了一些只提到日期floor/ceil
函数的网络教程:
using Dates
julia> floor(today(), Month) - Day(1)
2021-06-30
julia> typeof(ans)
Date
julia> floor(now(),Month) - Day(1)
2021-06-30T00:00:00
这很好用,我看不出它是如何失败的。但是,始终出色的 Julia 文档描述了用于此目的的专用函数。
julia> lastdayofmonth(today() - Month(1))
2021-06-30
# maybe a leap year would cause a problem
julia> lastdayofmonth(Date("20200331","yyyymmdd") - Month(1))
2020-02-29
julia> lastdayofmonth(Date("20200229","yyyymmdd") + Month(1))
2020-03-31
有许多有用的函数,例如 firstdayofmonth()
、dayofweek()
、isleapyear()
。看起来一切正常!
更正了以下错误,我在找到最后一天后减去了月份,在 postgres 中有效但在 Julia Dates 中无效:
# WRONG, works only if prior month is shorter
lastdayofmonth(today()) - Month(1)
lastdayofmonth(Date("20210228", "yyyymmdd")) - Month(1)
2021-01-28