将时间格式转换为Pandas中的小数

时间:2016-01-28 06:43:42

标签: python datetime pandas

我有一个数据框和一个名为" datetime"的数据框列。包含时间信息,例如" 2014-01-09 09:15:01"。我想做的是转换" 2014-01-09 09:15:01" to" 2014-01-09 09:15:01.000000"。 我做的是

data = pd.to_datetime(trade_data['datetime'], format="%Y-%m-%d %H:%M:%S%.f").

然而,它不起作用。

ValueError: time data '2014-01-20 07:05:36.500000' does not match format '%H:%M:%S.%f'

如何解决这个问题? THX。

编辑 “&date”'。

列中包含的内容
>>> data['datetime'][:20]
date
2014-01-20    2014-01-20 07:05:36.500000
2014-01-20    2014-01-20 09:14:00.500000
2014-01-20    2014-01-20 09:15:00.500000
2014-01-20           2014-01-20 09:15:01
2014-01-20    2014-01-20 09:15:01.500000
2014-01-20           2014-01-20 09:15:02
2014-01-20    2014-01-20 09:15:02.500000
2014-01-20           2014-01-20 09:15:03
2014-01-20    2014-01-20 09:15:03.500000
2014-01-20           2014-01-20 09:15:04
2014-01-20    2014-01-20 09:15:04.500000
2014-01-20           2014-01-20 09:15:05
2014-01-20    2014-01-20 09:15:05.500000
2014-01-20           2014-01-20 09:15:06
2014-01-20    2014-01-20 09:15:06.500000
2014-01-20           2014-01-20 09:15:07
2014-01-20    2014-01-20 09:15:07.500000
2014-01-20           2014-01-20 09:15:08
2014-01-20    2014-01-20 09:15:08.500000
2014-01-20    2014-01-20 09:15:09.500000
Name: datetime, dtype: object

2 个答案:

答案 0 :(得分:1)

您可以使用dt.strftime执行此操作:

s = pd.Series(["2014-01-09 09:15:01"])
s = pd.to_datetime(s)
res = s.dt.strftime("%Y-%m-%d %H:%M:%S.%f")

In [115]: res
Out[115]:
0    2014-01-09 09:15:01.000000
dtype: object

注意:它适用于pandas版本> = 0.17.0

修改

对于pandas版本< 0.17.0您可以使用datetime.strftimeapply

from datetime import datetime
res1 = s.apply(lambda x: datetime.strftime(x, "%Y-%m-%d %H:%M:%S.%f"))

In [250]: res1
Out[250]:
0    2014-01-09 09:15:01.000000
dtype: object

答案 1 :(得分:1)

您可以尝试map

print df
                              datetime
2014-01-20  2014-01-20 09:15:00.500000
2014-01-20         2014-01-20 09:15:01
2014-01-20  2014-01-20 09:15:01.500000
2014-01-20         2014-01-20 09:15:02

df['datetime'] = pd.to_datetime(df['datetime'])
print df
                          datetime
2014-01-20 2014-01-20 09:15:00.500
2014-01-20 2014-01-20 09:15:01.000
2014-01-20 2014-01-20 09:15:01.500
2014-01-20 2014-01-20 09:15:02.000

df['datetime'] = df['datetime'].map(lambda x: x.strftime('%Y-%m-%d %H:%M:%S.%f'))
print df
                              datetime
2014-01-20  2014-01-20 09:15:00.500000
2014-01-20  2014-01-20 09:15:01.000000
2014-01-20  2014-01-20 09:15:01.500000
2014-01-20  2014-01-20 09:15:02.000000