将字符串转换为日期格式:DD-MMM-YYYY 到 Python 中的日期时间

0 python string date dataframe pandas

我有一个包含如下字符串的列的熊猫数据框

01-May-2012  16:44:55.113
01-Jun-2012  18:49:57.466
01-May-2012  14:64:45.119
01-May-2012  14:23:55.113
Run Code Online (Sandbox Code Playgroud)

我想将其转换为以下格式。

2012-05-01 16:44:55.113
2012-06-01 18:49:57.466
2012-05-01 14:64:45.119
2012-05-01 14:23:55.113
Run Code Online (Sandbox Code Playgroud)

我尝试使用 pandas.to_datetime(df['date time']) 但我收到错误未知字符串值。我还尝试将字符串拆分为两列并仅转换日期部分,但遇到了类似的错误

Ant*_*vBR 6

可能是这样的:将 Pandas 列转换为 DateTime。它很旧,接受的答案指定了大多数情况下不需要的格式。

但是,看看这个:

import pandas as pd

data = dict(dates=['01-May-2012  16:44:55.113',
                   '01-Jun-2012  18:49:57.466',
                   '01-May-2012  14:64:45.119',  # <--- Error, minute can't be more than 60
                   '01-May-2012  14:23:55.113'])

df = pd.DataFrame(data)
df.dates = pd.to_datetime(df.dates, errors='coerce')

print(df)
Run Code Online (Sandbox Code Playgroud)

你得到了这个(感谢@3novak 建议使用 errors='coerce'):

                    dates
0 2012-05-01 16:44:55.113
1 2012-06-01 18:49:57.466
2                     NaT
3 2012-05-01 14:23:55.113
Run Code Online (Sandbox Code Playgroud)