'How do I convert the DataFrame's Date object to a datetime format for plotting?

I am using a data set from Yahoo Finance, about stock market data. I wanted to plot the close price of the stock vs. the date range. On the X-Axis I wanted the date values and on the Y-axis I wanted the close price.

This is the data frame I have:

Date Close Adj Close
0 03/04/2006 19.267448 9.831543
1 04/04/2006 19.413416 9.906025
2 05/04/2006 20.218927 10.317053
3 07/04/2006 19.899965 10.154296
4 10/04/2006 19.564787 9.983268

The data types used are:

  • Date: object
  • Close: float64
  • Adj Close: float64
  • dtype: object

I plot I got was: The plot of the close price, where X-Axis has numbers from 0 - 3500

dataframe name:df column name: Close

I tried the following code:

df['Date'] = pd.to_datetime(df['Date'], format='%d%b%Y:%H:%M:%S.%f')and got: ValueError: time data '03/04/2006' does not match format '%d%b%Y:%H:%M:%S.%f' (match)

I also tried:

df['Date'] = df['Date'].apply(pd.to_datetime) and got a ParserError: Unknown string format: 03/04/200604/04/2006



Solution 1:[1]

Use:

pd.to_datetime(df['date'])

without format parameter. Example:

df = pd.DataFrame({'date':['03/04/2006', '05/04/2006']})
pd.to_datetime(df['date'])

output:

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 keramat