Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the float value from datetime index

I have the following code:

import pandas as pd
import yfinance as yf
import datetime
from dateutil.relativedelta import relativedelta
import pandas as pd, mplfinance as mpf, matplotlib.pyplot as plt
import numpy as np

db = yf.download(tickers='goog', start=datetime.datetime.now()-relativedelta(days=7), end= datetime.datetime.now(), interval="5m")
db = db.dropna()

If i wanted to get the float value i would just do this "

db.index.get_loc(pd.Timestamp('2022-02-16 12:05:00'))

and it would produce 34
So :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

b =db[33:34]

But if i do this:

db.index.get_loc(pd.Timestamp(b.index.strftime('%Y-%m-%d %I:%M:%S')))

I get:

TypeError: Cannot convert input [Index(['2022-02-22 09:15:00'], dtype='object', name='Datetime')] of type <class 'pandas.core.indexes.base.Index'> to Timestamp

Could you please advise how can i get the index from datetime?

>Solution :

Here b.index.strftime('%Y-%m-%d %I:%M:%S') return one element Index, so for scalar need select first value:

b = db.iloc[33:34]
print (b)
                             Adj Close  Volume  
Datetime                                        
2022-02-16 12:15:00-05:00  2709.629883    8000  

print (b.index.strftime('%Y-%m-%d %I:%M:%S'))
Index(['2022-02-16 12:15:00'], dtype='object', name='Datetime')

print (b.index.strftime('%Y-%m-%d %I:%M:%S')[0])
2022-02-16 12:15:00

a = db.index.get_loc(pd.Timestamp(b.index.strftime('%Y-%m-%d %I:%M:%S')[0]))
print (a)
33
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading