获取自午夜以来在数据框中花费的时间 [英] Get the time spent since midnight in dataframe

查看:25
本文介绍了获取自午夜以来在数据框中花费的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,它有一列时间戳类型.我想找到自午夜以来经过的时间(以秒为单位)作为新列.如何以简单的方式做到这一点?

I have a dataframe which has a column of type Timestamp. I want to find the time elapsed (in seconds) since midnight as a new column. How to do it in a simple way ?

例如:输入:

samples['time']
2018-10-01 00:00:01.000000000
2018-10-01 00:00:12.000000000

<小时>

type(samples['time'].iloc[0])

<class 'pandas._libs.tslib.Timestamp'>

输出:

samples['time_elapsed']
1
12

推荐答案

当前答案过于复杂或专业化.

Current answers either too complicated or specialized.

samples = pd.DataFrame(data=['2018-10-01 00:00:01', '2018-10-01 00:00:12'], columns=['time'], dtype='datetime64[ns]')

samples['time_elapsed'] = ((samples['time'] - samples['time'].dt.normalize()) / pd.Timedelta('1 second')).astype(int)

print(samples)
                 time  time_elapsed
0 2018-10-01 00:00:01             1
1 2018-10-01 00:00:12            12

  • normalize() 从日期时间中删除时间组件(将时钟移回午夜).
  • pd.Timedelta('1 s') 设置度量单位,即 timedelta 中的秒数.
  • .astype(int) 将十进制秒数转换为 int.如果愿意,请使用圆形功能.
    • normalize() removes the time component from the datetime (moves clock back to midnight).
    • pd.Timedelta('1 s') sets the unit of measurement, i.e. number of seconds in the timedelta.
    • .astype(int) casts the decimal number of seconds to int. Use round functionality if that is preferred.
    • 这篇关于获取自午夜以来在数据框中花费的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆