Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert pandas freq string to timedelta

Tags:

python

pandas

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.

like image 624
M. Toya Avatar asked Jul 17 '15 06:07

M. Toya


People also ask

How do I convert to Timedelta?

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.

How do you convert seconds to HH MM SS in pandas?

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.

How do you use pandas Timedelta?

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 .

What does PD Timedelta do?

Timedelta. Represents a duration, the difference between two dates or times. Timedelta is the pandas equivalent of python's datetime.


1 Answers

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')
like image 187
joris Avatar answered Sep 23 '22 10:09

joris