21

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.

Community
  • 1
  • 1
M. Toya
  • 615
  • 8
  • 24

1 Answers1

37

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')
joris
  • 133,120
  • 36
  • 247
  • 202
  • 2
    Thanks, this answer really helped me. Note that many moons later, in pandas 2, `pd.to_timedelta('30T')` does work. Since when I'm not sure. – dougmet Jun 29 '23 at 20:46