M. Toya
M. Toya

Reputation: 715

Convert pandas freq string to timedelta

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.

Upvotes: 23

Views: 8251

Answers (1)

joris
joris

Reputation: 139292

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

Upvotes: 39

Related Questions