Splunk Search

How can I calculate the date difference by two timestamp?

sakuraWu1
New Member

Hi all,

I want to calculate the difference between dates within two different dates, my search is as below:

code 1:

| tstats min(_time) as first_time, max(_time) as last_time from datamodel=A by A.tag
| eval diff_date= (last_time- first_time)/ 86400

The result of code 1 can get some value, but it is not 100% accurate, for example, if my first_time is 10/23/2017 11:00pm and last_time is 10/24/2017 09:00am, the result I want is 1 day difference, I only focus on the date, but if I use above code, the date difference could be 0, cause it is within 24 hours.

code 2:

| tstats min(_time) as first_time, max(_time) as last_time from datamodel=A by A.tag
| eval first_date = strptime(first_time,"%Y-%m-%d") 
| eval last_date = strptime(last_time,"%Y-%m-%d") 
| eval diff = tostring((last_date-first_date), "duration")

I did a lot of research and someone mentioned that tostring function can also help. But my problem here is that I can't know why I can't get anything if I use strptime function, but I CAN get the correct date by using strftime function, however, still can't get anything for the diff column.

Can anyone Kindly help me on this? I really getting crazy trying to figure out this problem.

Thanks very much.

S

0 Karma

Sukisen1981
Champion

Code 1 eval first_date = strftime(first_time,"%Y-%m-%d-%H") | eval last_date = strftime(last_time,"%Y-%m-%d-%H")|eval firstdate = strptime(first_date,"%Y-%m-%d")|eval lastdate = strptime(last_date,"%Y-%m-%d-%H")|eval diff_date=(lastdate-firstdate)/86400 | fields diff_date

You can shorten the query of course, but remove |fields to see all fields and the calculations

0 Karma
Got questions? Get answers!

Join the Splunk Community Slack to learn, troubleshoot, and make connections with fellow Splunk practitioners in real time!

Meet up IRL or virtually!

Join Splunk User Groups to connect and learn in-person by region or remotely by topic or industry.

Get Updates on the Splunk Community!

Announcing Modern Navigation: A New Era of Splunk User Experience

We are excited to introduce the Modern Navigation feature in the Splunk Platform, available to both cloud and ...

Modernize your Splunk Apps – Introducing Python 3.13 in Splunk

We are excited to announce that the upcoming releases of Splunk Enterprise 10.2.x and Splunk Cloud Platform ...

Step into “Hunt the Insider: An Splunk ES Premier Mystery” to catch a cybercriminal ...

After a whole week of being on call, you fell asleep on your keyboard, and you hit a sequence of buttons that ...