Is it possible to convert frequencies represented by string such as "30T" (30 minutes) "2S" (2 seconds) to something that can be compared to a timedelta?
I am looking for a mechanism internal to pandas if possible. Coding all possible string conversion using mechanism such as these would not be robust.
The to_timedelta() function is used to convert argument to datetime. Timedeltas are absolute differences in times, expressed in difference units (e.g. days, hours, minutes, seconds). This method converts an argument from a recognized timedelta format / value into a Timedelta type. The data to be converted to timedelta.
Use the timedelta() constructor and pass the seconds value to it using the seconds argument. The timedelta constructor creates the timedelta object, representing time in days, hours, minutes, and seconds ( days, hh:mm:ss.ms ) format.
Using the top-level pd. to_timedelta , you can convert a scalar, array, list, or Series from a recognized timedelta format / value into a Timedelta type. It will construct Series if the input is a Series, a scalar if the input is scalar-like, otherwise it will output a TimedeltaIndex .
Timedelta. Represents a duration, the difference between two dates or times. Timedelta is the pandas equivalent of python's datetime.
In many cases, you can use the to_timedelta
function for this. It will convert a string to a timedelta:
In [9]: pd.to_timedelta('30min')
Out[9]: Timedelta('0 days 00:30:00')
In [10]: pd.to_timedelta('2S')
Out[10]: Timedelta('0 days 00:00:02')
However, it seems that pd.to_timedelta('30T') does not work, but this can maybe be regarded as a missing feature.
But, for this one it does work if you first convert it to a frequency object and then supply it to to_timedelta
:
In [19]: from pandas.tseries.frequencies import to_offset
In [20]: pd.to_timedelta(to_offset('30T'))
Out[20]: Timedelta('0 days 00:30:00')
If you start from a freqstr
from a DatetimeIndex, the second approach will always work. But, you can also use freq
instead of freqstr
, which returns a frequency object directly:
In [34]: dtidx = pd.date_range('2012-01-01', periods=5, freq='30min')
In [35]: pd.to_timedelta(dtidx.freq)
Out[35]: Timedelta('0 days 00:30:00')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With