Finding nearest time (poor title sorry)

Say I have the current time: 1745256344

And a string of times in seconds:

1745222400,1745244000,1745254800,1745305200,1745362800,1745398800,1745409600,1745478000,1745514000,1745564400,1745596800,1745650800,1745676000,1745730000,1745755200,1745780400,1745794800,1745834400,1745888400,1745910000,1745938800,1745967600,1745996400

How do I detect the closest times before and/or after the current time? In this case they’d be 1745254800,1745305200

I don’t know how to achieve this with my current knowledge.

Well if you subtract each of the times in the string from your current time and take the absolute value of that, then the smallest number will be the one that is the closest to the current time.

How do you work through the string. In Python there are for loops, but the for loops in KWGT are pretty nerfed…

Well it depends how your times are formatted and input, but I would suggest you look at the two Text Convert functions:
$tc(split, “SuperXOneXZed”, “X”, 1)$
$tc(json, “{‘a’:1,‘b’:2}”, “.a”)$
both of which would let you extract the times and then use an fl loop or even just a bunch of local variable results to compare.

I’d do it in 3 steps:

  1. Use fl() to transform each element in the list into <absolute difference> <separator> <sign> <separator> <original time> (where sign is 0 if time is in the past and 1 if time is in the future)
  2. Use tc(nsort) to sort that list by the first number that appears in it (the absolute difference)
  3. Use tc(reg) to extract the first item with the appropriate sign.

Assuming the string comes from a local variable called times (set using lv(times, <string>), accessed using #times), it would look something like this:

lv(now, df(S))
+ lv(transformed, tc(nsort, fl(0, tc(count, #times, ","), "i+1", 
  tc(reg, "
      lv(n, tc(split, '"+#times+"', i)) + 
      mu(abs, "+#now+" - #n) + @ + ("+#now+" - #n < 0) + @ + #n
    ",
    ', tc(utf, 22)
  ),
  ","
), ",")
/* get the first time in the past */
+ tc(reg, #transformed, "(^|.*?,)[^,]+@0@([^,]+)(,.*|$)", "$1")
/* get the first time in the future */
+ tc(reg, #transformed, "(^|.*?,)[^,]+@1@([^,]+)(,.*|$)", "$1")

Though this is untested so treat it as a proof of concept more than a finished product.

2 Likes