1

So I want to read csv and make a plot for the data. I use plotly candlestick to output stock data. However, some problems I met here very strange

start=datetime(2017,6,15,10,22)
end=datetime(2021,12,10,19,59)
df=pd.read_csv("test.csv")
df.head()

The output for dataframe that reading from excel is like this

        Date    Name    Open    High    Low Close
0   12/10/2021 19:59    Apple Inc   179.84  179.85  179.81  179.84
1   12/10/2021 19:58    Apple Inc   179.82  179.82  179.80  179.81
2   12/10/2021 19:57    Apple Inc   179.84  179.84  179.82  179.84
3   12/10/2021 19:56    Apple Inc   179.81  179.82  179.78  179.82
4   12/10/2021 19:55    Apple Inc   179.83  179.83  179.80  179.80

Here I am using strptime() to convert the data to datetime

dates1=df.iloc[:,0].tolist()
for i in range(len(dates1)):
    convertdates1.append(datetime.strptime(dates1[i],'%m/%d/%Y %H:%M'))

convertdates1[0]

But the output is wrong

datetime.datetime(2020, 11, 12, 0, 0)

You can see that 12/10/2021 19:59 was converted to 11/12/2020 00:00, why? How can I get the correct result? and I will need to use it on plotly candlestick function

fig=go.Figure(data=[go.Candlestick(x=convertdates1,open=open,close=close,high=high,low=low)])
fig.show()

Data sample if you need

Date,Name,Open,High,Low,Close
12/10/2021 19:59,Apple Inc,179.84,179.85,179.81,179.84
12/10/2021 19:58,Apple Inc,179.82,179.82,179.80,179.81
12/10/2021 19:57,Apple Inc,179.84,179.84,179.82,179.84
12/10/2021 19:56,Apple Inc,179.81,179.82,179.78,179.82

1 Answer 1

1

For me working perfectly in pandas alternative with to_datetime:

df.iloc[:,0] = pd.to_datetime(df.iloc[:,0], format='%m/%d/%Y %H:%M')
print (df)
                 Date       Name    Open    High     Low   Close
0 2021-12-10 19:59:00  Apple Inc  179.84  179.85  179.81  179.84
1 2021-12-10 19:58:00  Apple Inc  179.82  179.82  179.80  179.81
2 2021-12-10 19:57:00  Apple Inc  179.84  179.84  179.82  179.84
3 2021-12-10 19:56:00  Apple Inc  179.81  179.82  179.78  179.82

Testing your solution and also working well:

convertdates1 = []
dates1=df.iloc[:,0].tolist()
for i in range(len(dates1)):
    convertdates1.append(datetime.strptime(dates1[i],'%m/%d/%Y %H:%M'))

a = convertdates1[0]
print (a)
2021-12-10 19:59:00
Sign up to request clarification or add additional context in comments.

1 Comment

tried to_datetime() works well. It is a weird bug

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.