简体   繁体   中英

How to test if a time variable is in a series or not in python

Background: Sometimes we need to take a date which is a month after than the original timestamp, since not all days are trading days, some adjustments must be made.

I extracted the index of stock close price, getting a time series with lots of timestamps of trading days.

trading_day_glossory = stock_close_full.index

Now, given a datetime-format variable date , with the following function, the program should return me the day variable indicating a trading day. But indeed it did not. The if condition is never evoked, eventually it added up to 9999:99:99 and reported error.

def return_trading_day(day,trading_day_glossory): 
    while True:
        day = day + relativedelta(days=1)
        if day in trading_day_glossory:
            break

I reckon that comparing a timestamp with a datetime is problematic, so I rewrote the first part of my function in this way:

trading_day_glossory = stock_close_full.index
trading_day_glossory = trading_day_glossory.to_pydatetime()

# Error message: OverflowError: date value out of range

However this change makes no difference. I further tested some characteristics of the variables involved:

testing1 = trading_day_glossory[20] # returns a datetime variable say 2000-05-08 00:00:00
testing2 = day # returns a datetime variable say 2000-05-07 00:00:00

What may be the problem and what should I do? Thanks.

Not quite sure what is going on because the errors cannot be reproduced from your codes and variables.

However, you can try searchsorted to find the first timestamp not earlier than a given date in a sorted time series by binary search:

trading_day_glossory.searchsorted(day)

It's way better than comparing values in a while loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM