Anton Dovzhenko
Anton Dovzhenko

Reputation: 2569

How to get first day of year in KDB/Q?

I'm looking for efficient function to get the first day of year in Q. Like 2017.05.10 -> 2017.01.01 or 2016.08.19 -> 2016.01.01.

The next snippet works, but it is not efficient

{"D"$(string `year$x),".01.01"} .z.d

Upvotes: 1

Views: 3813

Answers (4)

Alexander Belopolsky
Alexander Belopolsky

Reputation: 2268

A common trick in this kind of calculations is to use the fact that unlike dates, months are very regular: each year has exactly 12 months. Thus to find the first day of the year, we first cast the date to the month type, then round it down to the multiple of 12 and cast back to the date type:

q)f:"d"$12 xbar"m"$
q)f .z.d
2017.01.01

or with the OP's dates:

q)f 2017.05.10 2016.08.19
2017.01.01 2016.01.01

Upvotes: 8

Thomas Smyth
Thomas Smyth

Reputation: 5644

Another solution for the sake of it:

{"d"$1+(-).`month`mm$x}.z.d
2017.01.01

Upvotes: 0

Jonathon McMurray
Jonathon McMurray

Reputation: 2981

Just to throw another variation into the mix:

q){.Q.addmonths[x;1-`mm$x]+1-`dd$x} .z.d
2017.01.01

Upvotes: 2

effbiae
effbiae

Reputation: 1157

for some of the range of "d":

q)"d"$ceiling 365.245*-2000+`year$.z.Z
2017.01.01

(dates are days from y2k)

Upvotes: 3

Related Questions