其他分享
首页 > 其他分享> > pd.to_timedelta() 将参数转换为timedelta计算时间差

pd.to_timedelta() 将参数转换为timedelta计算时间差

作者:互联网

pd.to_timedelta

将参数转换为timedelta,Timedelta在pandas中是一个表示两个datetime值之间的差(如日,秒和微妙)的类型,2个Datetime数据运算相减得出的结果就是一个Timedelta数据类型

pandas.to_timedelta(arg, unit=None, errors='raise')

参数:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

返回:

timedelta64 or numpy.array of timedelta64

例子

将单个字符串解析为Timedelta

pd.to_timedelta('1 days 06:05:01.00003')
#Timedelta('1 days 06:05:01.000030')
pd.to_timedelta('15.5us')
#Timedelta('0 days 00:00:00.000015500')

解析字符串列表或数组

pd.to_timedelta(['1 days 06:05:01.00003', '15.5us', 'nan'])
#TimedeltaIndex(['1 days 06:05:01.000030', '0 days #00:00:00.000015500', NaT],
#              dtype='timedelta64[ns]', freq=None)

通过指定unit关键字参数来转换数字

pd.to_timedelta(np.arange(5), unit='s')
'''
TimedeltaIndex(['0 days 00:00:00', '0 days 00:00:01', '0 days 00:00:02',
                '0 days 00:00:03', '0 days 00:00:04'],
               dtype='timedelta64[ns]', freq=None)
'''
pd.to_timedelta(np.arange(5), unit='d')
'''
TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'],
               dtype='timedelta64[ns]', freq=None)
'''

 

标签:00,timedelta,days,timedelta64,时间差,pd,arg
来源: https://www.cnblogs.com/cgmcoding/p/13714183.html