# Calculate duration using timestamps

**URL:** <https://discuss.elastic.co/t/calculate-duration-using-timestamps/91223>\
**Category:** Elasticsearch\
**Created:** [June 29, 2017, 5:23am UTC](https://discuss.elastic.co/t/calculate-duration-using-timestamps/91223 "2017-06-29T05:23:07Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![omsaran](https://avatars.discourse-cdn.com/v4/letter/o/f17d59/32.png) [@omsaran](https://discuss.elastic.co/u/omsaran)\
**Post date:** [June 29, 2017, 5:23am UTC](https://discuss.elastic.co/t/calculate-duration-using-timestamps/91223/1 "2017-06-29T05:23:07Z")

</div>

I have a device that can exist in multiple states (more than 2). Lets say it can exist in state1, state2, state3 and state4

I have a document that stores the timestamp of each state

```
{
   state1: time
   state3: time + 10
   state2: time + 20
   state4: time + 40
}

```

From the above document the duration of state1 is `state3 - state1`

Duration of state3 is `state2 - state3`

I want to calculate the aggregate duration of each state from multiple such documents. But the order in which the timestamps occur may not be the same.  
I basically want to calculate the duration of one state using the timestamp of the next state.

How do I do such aggregation in elasticsearch?

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [July 27, 2017, 5:23am UTC](https://discuss.elastic.co/t/calculate-duration-using-timestamps/91223/2 "2017-07-27T05:23:10Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
