Home > OS >  Get Timestamps of DatetimeIndex that are around Timestamp
Get Timestamps of DatetimeIndex that are around Timestamp

Time:05-05

I have a Timestamp object and a DatetimeIndex object:

Out[18]: Timestamp('2022-05-04 11:03:51.138289-0400', tz='America/Toronto')
Out[33]: DatetimeIndex(['2022-05-04 10:00:00-04:00', '2022-05-04 10:30:00-04:00',
                        '2022-05-04 11:00:00-04:00', '2022-05-04 11:30:00-04:00',
                        '2022-05-04 12:00:00-04:00', '2022-05-04 12:30:00-04:00',
                        '2022-05-04 13:00:00-04:00', '2022-05-04 13:30:00-04:00',
                        '2022-05-04 14:00:00-04:00', '2022-05-04 14:30:00-04:00',
                        '2022-05-04 15:00:00-04:00', '2022-05-04 15:30:00-04:00',
                        '2022-05-04 16:00:00-04:00'],
                       dtype='datetime64[ns, America/Toronto]', freq=None)

How can I get the Timestamp object within DatetimeIndex that is immediately before and immediately after Timestamp?

For example,

For:

Timestamp('2022-05-04 11:03:51.138289-0400', tz='America/Toronto')

Return:

DatetimeIndex(['2022-05-04 11:00:00-04:00', '2022-05-04 11:30:00-04:00'], 
              dtype='datetime64[ns, America/Toronto]', freq=None)

I can do something totally hacky like so:

import pandas
from pandas_market_calendars import get_calendar, date_range

tz = "America/Toronto"

nyse = get_calendar("NYSE")

now = pandas.Timestamp.now(tz=tz)
dti = date_range(nyse.schedule("2022-05-04", "2022-05-04"), frequency="30min").tz_convert(tz)
pre = []
post = []

print(now)

for i in dti:
    if i <= now:
        pre.append(i)
    if i >= now:
        post.append(i)

print(pre[-1])
print(post[0])
out:
2022-05-04 12:54:18.236651-04:00
2022-05-04 12:30:00-04:00
2022-05-04 13:00:00-04:00

But I feel like there are better ways to do this, be it list comprehension or some built-in pandas method that I'm unfamiliar with, or something else.

It was suggested that Converting between datetime, Timestamp and datetime64 could be an answer, but I don't believe it's appropriate. That question is around conversion, my question is around ranges.

CodePudding user response:

Assuming dti is sorted, one option is to use numpy.searchsorted because it finds the index in dti where now should be inserted to maintain order:

import numpy as np
idx = np.searchsorted(dti, now)
out = dti[idx-1:idx 1]

Output:

DatetimeIndex(['2022-05-04 11:00:00-04:00', '2022-05-04 11:30:00-04:00'], dtype='datetime64[ns, America/Toronto]', freq=None)
  • Related