6

is there a way to say that '13Min' is > '59S' and <'2H' using the frequency notation in pandas?

2 Answers 2

7
In [4]: from pandas.tseries.frequencies import to_offset

In [5]: to_offset('59s') < to_offset('1T')
Out[5]: True

In [6]: to_offset('13T') > to_offset('59s')
Out[6]: True

In [7]: to_offset('13T') < to_offset('59s')
Out[7]: False

In [8]: to_offset('13T') > to_offset('2H')
Out[8]: False

In [10]: to_offset('13T') < to_offset('2H')
Out[10]: True
2
  • 5
    This works until you start comparing e.g. month offsets: to_offset('M') > to_offset('W') throws TypeError: unorderable types: MonthEnd() > Week() Is there a way to compare these as well?
    – rixmit
    Commented Aug 3, 2017 at 12:49
  • Comparing offsets alone can lead to undetermined results: example comparing 2M and 60D depends really on which month you pick. I would say that up to weeks things go pretty smooth, after that you need a start date to compare, relative to your exact case see answer by @igor-pozdeev above
    – natbusa
    Commented Nov 23, 2021 at 5:47
5

Another way is to add both frequencies to one common date and compare the resulting instances of Timestamp. This also addresses @rixmit's comment.

In [2]: import pandas as pd
In [3]: from pandas.tseries.frequencies import to_offset

In [4]: common_dt = pd.to_datetime("2000-01-01")
In [5]: f_a = common_dt + to_offset('59s')
In [6]: f_b = common_dt + to_offset('1T')
In [7]: f_a > f_b
Out[8]: False

In [9]: f_a = common_dt + to_offset('M')
In [9]: f_b = common_dt + to_offset('W')
In [10]: f_a > f_b
Out[10]: True
1
  • This solution seems not to be working wtih 'W' and 'D'. common_dt = pd.to_datetime("2000-01-01") f_a = common_dt + to_offset('D') f_b = common_dt + to_offset('W') f_a == f_b
    – Ziur Olpa
    Commented Jul 31, 2022 at 15:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.