【问题标题】:How to remove seconds from timedelta variable?如何从 timedelta 变量中删除秒?
【发布时间】:2017-09-15 07:14:40
【问题描述】:

如何使用 python 从 timedelta 变量中删除秒和微秒。我有以下数据框,我想删除秒数。

df['Duration'] = ['03:12:37.771200','06:52:24.764500','13:19:57.325200','15:01:07.000200','04:05:06.722200','01:10:07.456200']

【问题讨论】:

  • 你之前问过这个问题...
  • 你认为是 datetime 还是 timedelta?
  • @jezrael 我已经编辑过了。谢谢
  • @WhatsThePoint 是的,但是另一个用户想提出一个不同的解决方案。那是日期时间变量,这是 timedelta。

标签: python pandas datetime


【解决方案1】:

round 方法与'T' 一起使用一分钟

df['Duration'] = pd.to_timedelta(df['Duration']).round('T')

print(df)

   Duration
0  03:13:00
1  06:52:00
2  13:20:00
3  15:01:00
4  04:05:00
5  01:10:00

你也可以使用floor

df['Duration'] = pd.to_timedelta(df['Duration']).floor('T')

print(df)

   Duration
0  03:12:00
1  06:52:00
2  13:19:00
3  15:01:00
4  04:05:00
5  01:10:00

【讨论】:

    【解决方案2】:

    如果需要将 timedelta 的秒数转换为numpy array,然后再转换为timedelta64[m]

    df['Duration'] = df['Duration'].values.astype("timedelta64[m]")
    

    dur = ['03:12:37.771200','06:52:24.764500','13:19:57.325200',
           '15:01:07.000200','04:05:06.722200','01:10:07.456200']
    df = pd.DataFrame({'Duration':dur})
    
    df['Duration'] = pd.to_timedelta(df['Duration']).values.astype("timedelta64[m]")
    print (df)
       Duration
    0  03:12:00
    1  06:52:00
    2  13:19:00
    3  15:01:00
    4  04:05:00
    5  01:10:00    
    

    【讨论】:

    • 这是我必须记住的另一件事。这会截断信息,如果需要,您将如何四舍五入到最接近的分钟?
    • 嗯,我认为这是两种不同的东西——修剪和圆形。圆形是你的解决方案,修剪我的。
    • pandas 有一个 floorround... 我只是想知道 numpy 等价于 round 是什么
    • 在我看来不,它类似于 .values.astype('<M8[m]' 的日期时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-30
    • 1970-01-01
    • 2013-01-04
    • 2022-06-28
    • 1970-01-01
    • 1970-01-01
    • 2012-12-07
    相关资源
    最近更新 更多