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 lookin
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')