Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build a Pandas pd.tseries.offsets from timedelta

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 ?

like image 436
Femto Trader Avatar asked Dec 12 '14 13:12

Femto Trader


2 Answers

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}>
like image 122
elyase Avatar answered Sep 20 '22 04:09

elyase


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>
like image 20
Little Bobby Tables Avatar answered Sep 22 '22 04:09

Little Bobby Tables