如何在 Pandas 中将字符串转换为时间戳

16

我有以下数据集

    OPEN TIME  CLOSE TIME
0   09:44:00   10:07:00
1   10:07:00   11:01:00
2   11:05:00   13:05:00

但是这里的时间戳是字符串格式,怎样将它们转换为时间格式?

2个回答

28

to_datetime

df['Open'] = pd.to_datetime(df['OPEN TIME'],format= '%H:%M:%S' ).dt.time
df['Close'] = pd.to_datetime(df['CLOSE TIME'],format= '%H:%M:%S' ).dt.time

3
“dt.time”是什么意思? - lifelonglearner
.dt.time 提取日期的小时/分钟/秒部分。这是必要的,因为 to_datetime 也会引入年/月/日信息。 - Yaniel Cabrera

1

可以使用apply在一行中转换两列。尝试一下:

df = df.assign(**df[['OPEN TIME', 'CLOSE TIME']].apply(pd.to_datetime, format='%H:%M:%S'))

要获取没有日期的时间,请使用以下方法:

# assign back to the columns   ---- sometimes, this case throws a SettingWithCopyWarning if `df` was filtered from another frame
df[['OPEN TIME', 'CLOSE TIME']] = df[['OPEN TIME', 'CLOSE TIME']].apply(lambda x: pd.to_datetime(x, format='%H:%M:%S').dt.time)

# or call assign and create a new dataframe copy  ---- this case never throws a warning
df = df.assign(**df[['OPEN TIME', 'CLOSE TIME']].apply(lambda x: pd.to_datetime(x, format='%H:%M:%S').dt.time))

这将每个字符串转换为datetime.time对象。然而,由于datetime.time没有相应的pandas数据类型,因此很难利用矢量化操作。例如,不可能在datetime.time对象之间找到时间差(因此与字符串相比没有太大改进),但如果它们是datetime64,则可以。例如,以下创建datetime64

df1 = df.assign(**df[['OPEN TIME', 'CLOSE TIME']].apply(pd.to_datetime, format='%H:%M:%S'))
df1['CLOSE TIME'] - df1['OPEN TIME']

0   0 days 00:23:00
1   0 days 00:54:00
2   0 days 02:00:00
dtype: timedelta64[ns]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接