【问题标题】:How to convert a datetime format to minutes - pandas如何将日期时间格式转换为分钟 - 熊猫
【发布时间】:2018-10-27 19:14:27
【问题描述】:

我有一个数据框,其中有一列 usage_duration(这是日期时间格式的另外两列的差异)。如下所示:

processid, userid, usage_duration 
17613,root,0 days 23:41:03.000000000
17641,root,2 days 04:05:26.000000000
13848,acs,0 days 00:00:50.000000000
3912,acs,0 days 06:07:38.000000000
6156,acs,0 days 17:22:43.000000000

现在我想将其转换为分钟。它应该如下所示:

processid, userid, usage_duration_min
17613,root,1421
17641,root,3125
13848,acs,0
3912,acs,367
6156,acs,1042

谁能告诉我这怎么可能?

非常感谢您的支持

【问题讨论】:

标签: python python-3.x pandas datetime series


【解决方案1】:

使用total_secondsseconds 除以60,最后转换为integers:

#if necessary converting to timedelta
#df['usage_duration'] = pd.to_timedelta(df['usage_duration'])

df['new'] = df['usage_duration'].dt.total_seconds().div(60).astype(int)

或者:

 df['new'] = (df['usage_duration'].dt.seconds.div(60).astype(int) 
             + df['usage_duration'].dt.days.multiply(1440).astype(int) )

print (df)
   processid userid  usage_duration   new
0      17613   root 0 days 23:41:03  1421
1      17641   root 2 days 04:05:26  3125
2      13848    acs 0 days 00:00:50     0
3       3912    acs 0 days 06:07:38   367
4       6156    acs 0 days 17:22:43  1042

【讨论】:

  • 此建议有效,但 2 天没有转换。例如在第二行,它只转换 04:05:26
  • df['new'] = df['usage_duration'].dt.seconds.div(60).astype(int)+df['usage_duration'].dt.days.multiply(1440 ).astype(int)
  • @JitheshErancheri - 谢谢,我改变了答案。
【解决方案2】:

这是一种方式:

s = pd.Series(['0 days 23:41:03.000000000', '2 days 04:05:26.000000000',
               '0 days 00:00:50.000000000', '0 days 06:07:38.000000000',
               '0 days 17:22:43.000000000'])

s = pd.to_timedelta(s).astype('timedelta64[m]').astype(int)

print(s)

0    1421
1    3125
2       0
3     367
4    1042
dtype: int32

【讨论】:

    猜你喜欢
    • 2021-09-22
    • 2015-09-22
    • 2021-10-21
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 2018-12-08
    相关资源
    最近更新 更多