使用 pandas 将日期时间值四舍五入到前30秒 [英] Round down datetime values to previous 30 seconds using pandas
问题描述
给出的时间戳以秒为单位.例如:
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)#不起作用..
使用 有关日期/时间频率的更多信息,您可以在此处使用,请查看偏移别名. 如果要将其编写为可重用函数,请修改代码以接受两个参数: 样品运行 它在其他频率下也很好用, The Time Stamp give is in Seconds Precision.
Eg: Give One Function may be applied is Challenge is to call the function, like
Use 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: Sample run, It works nicely for other frequencies as well,
这篇关于使用 pandas 将日期时间值四舍五入到前30秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
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]
myTime myVal
2019-06-03 11:47:37 0.34
2019-06-03 11:47:12 0.32
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.def timeAdjust(numSec):
if numSec > 30:
numSec = 30
else:
numSec = 0
numSec
timeAdjust(df['myTime'].seconds) # Does not work ..
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]
qualifier
, and freq
denoting the scale and frequency respectively.def adjust_time(ser, qualifier, freq=1):
return ser.dt.floor(f'{freq}{qualifier}')
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]
adjust_time(pd.to_datetime(df['myTime']), qualifier='D')
0 2019-06-03
1 2019-06-03
Name: myTime, dtype: datetime64[ns]