Search code examples
pythonpandasdataframetimezone

Indexing a Timezone-aware Datetime index


I have a simple code (that worked fine) for grabbind the dividend data from yfinance. The code takes te dividend data from the start to end date (which is by default set to today). I am using Python 3.10.12

The code is

import pandas as pd
import yfinance as yf
import datetime
from datetime import timedelta

st_dni = 1000
end = datetime.date.today()                               
start = end - timedelta(days = st_dni)
ticker=('XOM')

stock = yf.Ticker(ticker)
temp = pd.DataFrame(stock.dividends)
div = temp.loc[start:end]

print(div)

The line in question is temp.loc[start:end]. It returns a Futurewarning regarding Timezone naive datetime since it is deprecated. Is there and alternative to this? How can I select dividends from the Temp DataFrame within the selected dates?


Solution

  • You could try using a string:

    div = temp.loc[str(start):str(end)]
    

    Output:

                               Dividends
    Date                                
    2021-11-10 00:00:00-05:00       0.88
    2022-02-09 00:00:00-05:00       0.88
    2022-05-12 00:00:00-04:00       0.88
    2022-08-11 00:00:00-04:00       0.88
    2022-11-14 00:00:00-05:00       0.91
    2023-02-13 00:00:00-05:00       0.91
    2023-05-15 00:00:00-04:00       0.91
    2023-08-15 00:00:00-04:00       0.91
    2023-11-14 00:00:00-05:00       0.95
    2024-02-13 00:00:00-05:00       0.95
    2024-05-14 00:00:00-04:00       0.95
    

    IMHO this is the easiest way.