首页 > 解决方案 > 如何在 Python 中将字符串时间戳转换为日期时间对象

问题描述

我有一个带有时间戳字符串的 pandas 列,格式为“00:00:00.000”(小时、分钟、秒、微秒)。我想将它们转换为datetime对象以在秒上工作。

例如,我在这里看到了许多类似的问题。我猜我应该使用strptime,但我不知道如何使用。

标签: python-3.xpandasdatetime

解决方案


如果在 pandas 中将值转换为日期时间,还会添加一些默认值dateto_datetime

df['col'] = pd.to_datetime(df['col'], format='%H:%M:%S.%f')

如果需要避免它通过以下方式将值转换为 timedeltas to_timedelta

df['col'] = pd.to_timedelta(df['col'])

推荐阅读