给定日期列表,获取每月最后 n 天

Get last n days per month given a list of dates

如何提取日期列表中每个月的最后 n 天?

假设我有以下日期列表:

dates:2000.01.01 + til 60

n:2.

我想要的预期结果是:

2000.01.30 2000.01.31 2000.02.28 2000.02.29

您想为每个日期构建一个月份字典,然后将完成的 it.Once 分组,您可以使用 # 运算符。更新:子列表可能是更好的运算符,以处理可能的重复项,这取决于传入的数据

// Build the dictionary/mapping
q)dates!`month$dates
2000.01.01| 2000.01
2000.01.02| 2000.01
2000.01.03| 2000.01
2000.01.04| 2000.01

// Group the results
q)group dates!`month$dates
2000.01| 2000.01.01 2000.01.02 2000.01.03 2000.01.04 2000.01.05 2000.01.06 20..
2000.02| 2000.02.01 2000.02.02 2000.02.03 2000.02.04 2000.02.05 2000.02.06 20..

// Act on each month
q)-2#/:group dates!`month$dates
2000.01| 2000.01.30 2000.01.31
2000.02| 2000.02.28 2000.02.29

// Raze the results
q)raze value -2#/:group dates!`month$dates
2000.01.30 2000.01.31 2000.02.28 2000.02.29

总而言之,您通过转换日期构建日期到相应月份的映射,然后对它们进行分组。完成后,您可以提取结果。您需要确保在对日期进行操作之前对其进行排序。

我们可以把这一切放到一个漂亮的函数中,名字不祥 lastDays

q)lastDays:{[dts;n] raze value (neg n)#/:group dts!`month$dts}
q)lastDays[dates;2]
2000.01.30 2000.01.31 2000.02.28 2000.02.29

根据 Terry 的建议编辑为利用子列表而不是#

q)lastDays:{[dts;n] raze value sublist/:[neg n;]group dts!`month$dts}
q)lastDays[dates;2]
2000.01.30 2000.01.31 2000.02.28 2000.02.29