【问题标题】:How to Retrieve Just the Time from DateTime Object but retaining the datatype如何仅从 DateTime 对象中检索时间但保留数据类型
【发布时间】:2021-02-28 09:21:05
【问题描述】:

我有一些时间戳数据。我将其类型从字符串更改为datetime。它看起来像这样:

1    2020-11-06 09:42:13.830995
2    2020-11-06 09:42:14.195429
3    2020-11-06 09:42:14.378181
4    2020-11-06 09:42:36.801859
                ...            
59   2020-11-06 10:30:06.299660
60   2020-11-06 10:31:13.824763
61   2020-11-06 10:31:21.924866
62   2020-11-06 10:31:23.016526
63   2020-11-06 10:34:21.289348
Name: timestamp, Length: 64, dtype: datetime64[ns]

有没有办法只从datetime 数据中检索时间部分,结果是相同的数据类型。?我是这样做的: df.timestamp.dt.time 得到想要的结果:

1     09:42:13.830995
2     09:42:14.195429
3     09:42:14.378181
4     09:42:36.801859
           ...       
59    10:30:06.299660
60    10:31:13.824763
61    10:31:21.924866
62    10:31:23.016526
63    10:34:21.289348
Name: Log_Timestamp, Length: 64, dtype: object

但是如您所见,数据类型不再是 datetime

谢谢

谢谢

【问题讨论】:

  • 应该是python对象time不是日期时间。
  • 在 pandas 中,您不能单独拥有日期和时间。只需使用 datetime 并忽略日期部分。

标签: python pandas datetime timestamp


【解决方案1】:

预计,python 对象time 不是datetime

关闭,你需要的是timedeltas:

pd.to_timedelta(df.timestamp.dt.strftime('%H:%M:%S'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-04
    • 1970-01-01
    • 2017-08-15
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多