Starlark Processor: Convert epoch time to standard time format

Is it possible to use the Starlark processor to convert epoch time to standard time?

I have a ‘last-established’ field that comes in with a value of ‘1632815873325776000’.
I’d like to figure out how to convert this time to:

“Tuesday, September 28, 2021 3:57:53.325 AM GMT-04:00 DST”

Thank you.

Hi @mohsin106 ,
Nice to meet you digitally. Check out this Stackoverflow conversation:

The time library comes preloaded with the Starlark plugin. You will be looking to use
time.parse_time() function.

Let me know if this helps

Many thanks,
Jay

You might also find all examples in telegraf/plugins/processors/starlark/testdata at master · influxdata/telegraf · GitHub starting with time_ helpful…

1 Like

Hi @Jay_Clifford ,
I tried following the article you sent but that did not help.
This is what my starlark script looks like:

load("time.star", "time")
load("logging.star", "log")

def apply(metric):
    for k, v in metric.fields.items():
        # log.debug("This is k: {}".format(k))
        if k == "last-established":
            epochDate = metric.fields["last-established"]
            newDate = time.parse_time(str(epochDate), format="2006-01-02T15:04:05.999999999", location="UTC")
            metric.fields["test-data"] = newDate
    return [metric]

I get the following error message:

2021-10-22T15:39:42Z E! [processors.starlark] Error in parse_time: parsing time "1632299576746236416" as "2006-01-02T15:04:05.999999999": cannot parse "299576746236416" as "-"
2021-10-22T15:39:42Z E! [processors.starlark] Error in plugin: parsing time "1632299576746236416" as "2006-01-02T15:04:05.999999999": cannot parse "299576746236416" as "-"

So after tinkering with Starlark and my data set for a few hours, I was able to figure out how to convert epoch time to regular time. Here is my working solution:

[[processors.starlark]]
namepass = ["bgp"]
  source = '''
load("time.star", "time")
load("logging.star", "log")
def apply(metric):
  for k, v in metric.fields.items():
    # log.debug("This is k: {}".format(k))
    if k == "neighbors/neighbor/state/last_established":
      new_date = time.from_timestamp(int(v / 1e9))
      metric.fields.pop(k)
      metric.fields["last-established"] = str(new_date)
      # log.debug("This is last-established: {}".format(metric.fields.get("last-established")))
  return [metric]
'''
1 Like

Hi @mohsin106,
My apologies I was on annual leave. Awsome news you got it to work and many thanks for contributing back to us your answer!