The Pandas function to_timedelta() used to convert specified argument to timedelta. The delta represents the absolute differences in times, expressed in difference units, ie. days, hours, minutes, seconds. It returns timedelta, if it parses successfully, depending on type.
It can be returns
1. | list : TimedeletaIndex of timedelta64 dtype |
2. | Series : Series of timedelta64 dtype |
3. | scalar : Timedeleta |
1 Pandas.to_timedelta(arg, unit = None, errors = 'raise')
unit : It is string that represents the unit of the argument for numeric arg. If not specified the default value will be ns.
error : It is string that represents what to do when an error occur. If not specified, the default value will be raise.
1. | raise : If specified, It raise an exception when invalid parse. |
2. | coerce : If specified, It sets a NaT when invalid parse. |
3. | ignore : If specified, It returns the input(original) when invalid parse. |
to_timedelta() with scalar
to_timedelta() with scalar
1 import pandas as pd
2
3 res1 = pd.to_timedelta('2 days 04:23:23.00005')
4 print('The converted timedelta :')
5 print(res1)
6
7 res2 = pd.to_timedelta('23.5us')
8 print('The converted timedelta :')
9 print(res2)
In the above example, a to_timedelta() function is called by passing a scalar value that convert specified value to timedelta that assign to the variable that will be printed on console.
1 The converted timedelta :
2 2 days 04:23:23.000050
3
4 The converted timedelta :
5 0 days 00:00:00.000023500
to_timedelta() with iterables
to_timedelta() with iterables
1 import pandas as pd
2 import numpy as np
3
4 res1 = pd.to_timedelta(['2 days 04:23:23.00005', 'nan', '23.5us'])
5 print('The converted timedelta :')
6 print(res1)
7
8 res2 = pd.to_timedelta(np.arange(5), unit = 's')
9 print('The converted timedelta :')
10 print(res2)
11
12 res3 = pd.to_timedelta(np.arange(5), unit = 'd')
13 print('The converted timedelta :')
14 print(res3)
In the above example, a to_timedelta() function is called by passing an array or list that convert timedelta based on specified value and unit.
1 The converted timedelta :
2 TimedeltaIndex(['2 days 04:23:23.000050', NaT, '0 days 00:00:00.000023500'],
3 dtype='timedelta64[ns]', freq=None)
4
5 The converted timedelta :
6 TimedeltaIndex(['0 days 00:00:00', '0 days 00:00:01', '0 days 00:00:02', '0 days 00:00:03',
7 '0 days 00:00:04'],
8 dtype='timedelta64[ns]', freq=None)
9
10 The converted timedelta :
11 TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'],
12 dtype='timedelta64[ns]', freq=None)
Related options for your search