如何使用熊猫将月份名称和年份转换为日期时间

时间:2020-05-26 18:13:46

标签: python pandas dataframe datetime

我正在尝试使用熊猫将数据框的索引转换为日期时间对象,但始终收到此错误-

“ ValueError:时间数据'Jan 20'与格式'%b,%y'(匹配)不匹配”。

我仔细检查了日期时间格式并删除了连字符,但还是没有运气。我怎样才能解决这个问题?

这是我尝试过的:

import pandas as pd

table = pd.read_html('https://www.finra.org/investors/learn-to-invest/advanced-investing/margin-statistics')

#set the index to date column
df = table[0].set_index('Month/Year')

df.index = df.index.str.replace("-", " ")

df.index = pd.to_datetime(df.index, format="%b, %y")

2 个答案:

答案 0 :(得分:1)

我认为您还有一个逗号。这对我来说很好:

df.index = pd.to_datetime(df.index, format="%b %y")

print(df.index)

输出:

DatetimeIndex(['2020-01-01', '2020-02-01', '2020-03-01', '2020-04-01'], dtype='datetime64[ns]', name='Month/Year', freq=None)

答案 1 :(得分:1)

小变化:

df.index = pd.to_datetime(df.index, format="%b-%y")
print(df)

            Debit Balances in Customers' Securities Margin Accounts  ...  Free Credit Balances in Customers' Securities Margin Accounts
Month/Year                                                           ...
2020-01-01                                             561812        ...                                             186847
2020-02-01                                             545127        ...                                             197716
2020-03-01                                             479291        ...                                             226202
2020-04-01                                             524696        ...                                             217187

[4 rows x 3 columns]
相关问题