使用 pandas 将日期时间值四舍五入到前30秒 [英] Round down datetime values to previous 30 seconds using pandas

查看:34
本文介绍了使用 pandas 将日期时间值四舍五入到前30秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出的时间戳以秒为单位.例如:

  myTime myVal2019-06-03 11:47:37 0.342019-06-03 11:47:12 0.32 

给出 myTime DateTime 对象想要将时间调整为 2019-06-03 11:47:30 2019-06-03 11:47:00 ,即以前的30秒精度./p>

一个功能可能被应用

  def timeAdjust(numSec):如果numSec>30:numSec = 30别的:numSec = 0numSec 

挑战就是像这样调用函数

  timeAdjust(df ['myTime'].seconds)#不起作用.. 

解决方案

使用

  pd.to_datetime(df ['myTime']).dt.floor('30s')0 2019-06-03 11:47:301 2019-06-03 11:47:00名称:myTime,dtype:datetime64 [ns] 

有关日期/时间频率的更多信息,您可以在此处使用,请查看偏移别名.


如果要将其编写为可重用函数,请修改代码以接受两个参数: qualifier freq 分别表示比例和频率.

  def Adjust_time(ser,qualifier,freq = 1):返回ser.dt.floor(f'{freq} {qualifier}') 

样品运行

  adjust_time(pd.to_datetime(df ['myTime']),qualifier ='s',freq = 30)0 2019-06-03 11:47:301 2019-06-03 11:47:00名称:myTime,dtype:datetime64 [ns] 

它在其他频率下也很好用,

  adjust_time(pd.to_datetime(df ['myTime']),qualifier ='D')0 2019-06-031 2019-06-03名称:myTime,dtype:datetime64 [ns] 

The Time Stamp give is in Seconds Precision. Eg:

myTime                 myVal
2019-06-03 11:47:37    0.34
2019-06-03 11:47:12    0.32

Give myTime is DateTime object Would like to adjust the time as 2019-06-03 11:47:30 , 2019-06-03 11:47:00 ie to previous 30 Second Precision.

One Function may be applied is

def timeAdjust(numSec):
    if numSec > 30:
        numSec = 30
    else:
        numSec = 0
    numSec

Challenge is to call the function, like

timeAdjust(df['myTime'].seconds) # Does not work ..

解决方案

Use dt.floor with "30s":

pd.to_datetime(df['myTime']).dt.floor('30s')

0   2019-06-03 11:47:30
1   2019-06-03 11:47:00
Name: myTime, dtype: datetime64[ns]

For more information regarding date/time frequencies you can use here, check out Offset Aliases.


If you want to write this as a reusable function, modify your code to accept two arguments: qualifier, and freq denoting the scale and frequency respectively.

def adjust_time(ser, qualifier, freq=1):
    return ser.dt.floor(f'{freq}{qualifier}')

Sample run,

adjust_time(pd.to_datetime(df['myTime']), qualifier='s', freq=30)

0   2019-06-03 11:47:30
1   2019-06-03 11:47:00
Name: myTime, dtype: datetime64[ns]

It works nicely for other frequencies as well,

adjust_time(pd.to_datetime(df['myTime']), qualifier='D')

0   2019-06-03
1   2019-06-03
Name: myTime, dtype: datetime64[ns]

这篇关于使用 pandas 将日期时间值四舍五入到前30秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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