【问题标题】:pandas datetime to transform new date format (hour-minute-second)?pandas datetime 转换新的日期格式(小时-分钟-秒)?
【发布时间】:2023-03-23 19:35:01
【问题描述】:

我想在新系列df['t'](例如 00:02:58)中将df['time'] 转换为时-分-秒格式。

1713   2019-09-24 00:02:58
1714   2019-09-24 00:12:11
1715   2019-09-24 00:13:42
……
Name: time, dtype: datetime64[ns]

尝试:

pd.to_datetime(df['time'],format='%H:%M:%S') 仍然得到相同的格式。

1713   2019-09-24 00:02:58
1714   2019-09-24 00:12:11
1715   2019-09-24 00:13:42
……
Name: time, dtype: datetime64[ns]

更新:

我想要日期时间格式。

【问题讨论】:

  • 那你的专栏不是已经是日期时间格式了吗?
  • 是的,原始列格式是日期时间。

标签: pandas


【解决方案1】:

我更喜欢timedelta:

df['new_time'] = df['time'] - df['time'].dt.normalize()

输出:

                    time new_time
1713 2019-09-24 00:02:58 00:02:58
1714 2019-09-24 00:12:11 00:12:11
1715 2019-09-24 00:13:42 00:13:42

然后您可以轻松访问其他信息,例如

df.new_time.dt.seconds

给予:

1713    178
1714    731
1715    822
Name: new_time, dtype: int64

【讨论】:

    【解决方案2】:

    试试dt.time

    df['time'] = df['time'].dt.time
    

    【讨论】:

    猜你喜欢
    • 2021-12-27
    • 1970-01-01
    • 2012-08-29
    • 1970-01-01
    • 1970-01-01
    • 2010-11-13
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    相关资源
    最近更新 更多