Splunk Search

How to subtract dates from two iso 8601 date fields in order to find the duration?

aahmad
Loves-to-Learn Everything

Hey, I am working on making a dashboard and wanted to know how can I subtract two dates that are in iso 8601 format. 

Please refer to the snippet of json below:

{ "startTime": "2022-04-25T01:02:19.221Z", "endTime": "2022-04-25T01:57:59.417Z"}

Labels (3)
0 Karma

richgalloway
SplunkTrust
SplunkTrust

Dates must be converted into epoch (integer) form before they can be subtracted.  Use the strptime function to do that.

| eval st=strptime(startTime, "%Y-%m-%dT%H:%M:%S.%3N%Z"), et=strptime(endTime, "%Y-%m-%dT%H:%M:%S.%3N%Z")
| eval diff = et - st
---
If this reply helps you, Karma would be appreciated.
0 Karma

aahmad
Loves-to-Learn Everything

@richgalloway  I tried your solution. My only problem is that when I do "table diff" in the end. I see empty fields. Do you know how can I fix that?

0 Karma

richgalloway
SplunkTrust
SplunkTrust

A null diff field means the et and/or st fields were null, which probably means the startTime/endTime fields were never extracted.  There are several ways to extract the fields, but I like to use rex.

{ "startTime": "2022-04-25T01:02:19.221Z", "endTime": "2022-04-25T01:57:59.417Z"}

| rex "startTime\\\":\\\"(?<startTime>[^\\\"]+)\\\",\\\"endTime\\\":\\\"(?<endTime>[^\\\"]+))"
| eval st=strptime(startTime, "%Y-%m-%dT%H:%M:%S.%3N%Z"), et=strptime(endTime, "%Y-%m-%dT%H:%M:%S.%3N%Z")
| eval diff = et - st
---
If this reply helps you, Karma would be appreciated.
0 Karma
Get Updates on the Splunk Community!

Splunk Observability for AI

Don’t miss out on an exciting Tech Talk on Splunk Observability for AI!Discover how Splunk’s agentic AI ...

Splunk Enterprise Security 8.x: The Essential Upgrade for Threat Detection, ...

Watch On Demand the Tech Talk on November 6 at 11AM PT, and empower your SOC to reach new heights! Duration: ...

Splunk Observability as Code: From Zero to Dashboard

For the details on what Self-Service Observability and Observability as Code is, we have some awesome content ...