首页 > 解决方案 > 带有时间戳的熊猫数据框 - 仅提取时间

问题描述

如何仅从 pandas 数据框中表示为 unix 时间的时间字段值中提取时间。

即从 2021 年 8 月 29 日上午 11:22:22.942 的 1630236142.942 开始,我只想要 11:22:22.942

编辑:

pd.to_datetime(df['time'], unit='s').time()

正在产生错误AttributeError: 'Series' object has no attribute time

标签: pythonpandasdatetime

解决方案


你可以这样做:

from datetime import datetime

# this line converts the string object in Timestamp object
df['DateTime'] = [datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') 
                  for d in df["DateTime"]]

# this line extract time from Timestamp object
df['Time'] = [datetime.strptime(d, "%Y-%m-%d %H:%M:%S").time()
              for d in df['DateTime']]  

推荐阅读