Python Pandas:字符串到日期时间

Tuu*_*nas 2 python datetime type-conversion pandas

我有一个带有字符串格式的datetime列的Pandas数据框。格式如下:

06 Feb 2014 12:09:42:000
Run Code Online (Sandbox Code Playgroud)

我需要将其转换为日期时间。现在我有:

df['date'] = pd.to_datetime(df['STARTDATE'],format='')
Run Code Online (Sandbox Code Playgroud)

我的问题是,我不知道要在format参数中放置什么以正确解析字符串。可以做到这一点,还是有更好的功能要使用?

jez*_*ael 6

您可以检查http://strftime.org/并使用:

df['date'] = pd.to_datetime(df['STARTDATE'],format='%d %b %Y %H:%M:%S:%f')
Run Code Online (Sandbox Code Playgroud)

样品:

df = pd.DataFrame({'STARTDATE':['06 Feb 2014 12:09:42:000','06 Mar 2014 12:09:42:000']})
print (df)
                  STARTDATE
0  06 Feb 2014 12:09:42:000
1  06 Mar 2014 12:09:42:000

df['date'] = pd.to_datetime(df['STARTDATE'],format='%d %b %Y %H:%M:%S:%f')
print (df)
                  STARTDATE                date
0  06 Feb 2014 12:09:42:000 2014-02-06 12:09:42
1  06 Mar 2014 12:09:42:000 2014-03-06 12:09:42
Run Code Online (Sandbox Code Playgroud)