Search code examples
pandasdatetimetimestamppython-datetimetimedelta

python how to get the day in the median between two days


I have two timestamps:

t1 = Timestamp('2020-01-01 00:00:00')
t2 = Timestamp('2020-01-07 06:00:00')]

I want to get the timestamp that is exactly in the middle between them, with one hour resolution:

tm = Timestamp('2020-01-04 03:00:00')]

if the number of timestamps is not odd (2 values in the middle), just pick one of the two.


Solution

  • This is actually quite easy with timestamps:

    The difference between the two timestamps can be computed by t2 - t1. Half of this can be computed by (t2 - t1) / 2. Now round this by using .floor('H'). This needs to be added by t1 and you got your result!

    tm = t1 + ((t2 - t1) / 2).floor('H')