I'd like to build a Pandas pd.tseries.offsets
from a datetime.timedelta
In [1]: from pandas.tseries.frequencies import to_offset
In [2]: import datetime
In [3]: td = datetime.timedelta(hours=1)
In [4]: to_offset('1H')
Out [4]: <Hour>
In [5]: to_offset(td)
Out [5]: ValueError
Any (other) idea ?
to_offset
returns a pd.DateOffset
. So you can directly build this object:
>>> td = datetime.timedelta(hours=1)
>>> pd.DateOffset(seconds=td.total_seconds())
<DateOffset: kwds={'seconds': 3600.0}>
>>> to_offset(pd.DateOffset(seconds=td.total_seconds()))
<DateOffset: kwds={'seconds': 3600.0}>
For a slightly nicer string representation:
>>> pd.DateOffset(days=td.days,
hours=td.seconds // 3600,
minutes=(td.seconds // 60) % 60)
<DateOffset: kwds={'hours': 1, 'minutes': 0, 'days': 0}>
This now works for pandas 23.x. I could not find when it was introduced.
from pandas.tseries.frequencies import to_offset
td = datetime.timedelta(hours=1)
to_offset('1H')
>>> <Hour>
to_offset(td)
>>> <Hour>
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