1

If I have a variable (in pd.datetime format):

date_value = pd.to_datetime("2019-12-10 10:57:00")

... how can I subtract a pandas frequency value from that datetime? For example, I may want to subtract "1min", or "15min", or "1B", or "1W" from that value.

These frequency values are stored as strings, and instead of parsing each string value for the integer and time value (min, day, week, etc.) which would be annoying, I'm wondering if there's a way to utilize the freq string values directly. Pseudo-code would look something like this:

new_date_value = date_value - timedelta("1min")

...but of course timedelta doesn't use the freq strings. Is there another way to do this?

wildcat89
  • 1,159
  • 16
  • 47
  • 1
    Use `pd.Timedelta()` or `pd.to_timedelta` instead? – Quang Hoang Jul 25 '22 at 03:20
  • 2
    Pandas handles this fine `date_value - pd.Timedelta('1min')`. I'm not sure what 1B is but the rest work as is. – Henry Ecker Jul 25 '22 at 03:21
  • Didn't even know about pandas' timedelta! Thanks for the easy answer!!! – wildcat89 Jul 25 '22 at 03:29
  • @HenryEcker `B` should be business day, as denoted here: https://pandas.pydata.org/pandas-docs/dev/user_guide/timeseries.html#offset-aliases HOWEVER, `Timedelta` doesn't understand it as `B` is an invalid argument as shown here: https://pandas.pydata.org/docs/reference/api/pandas.Timedelta.html, which SUCKS because I need BUSINESS DAY for my dataset! lol – wildcat89 Jul 25 '22 at 03:39
  • 1
    Hm. Yeah. Offsets are different than timedeltas. Timedelta are a fixed amount of time and are reduced to numeric values for faster computation. I'm not sure you'll find timedelta support for variable ranges like business days. Naturally `date_value - pd.offsets.BDay(1)` works, but I don't know if offsets has a string parser. – Henry Ecker Jul 25 '22 at 03:48
  • 1
    I literally just saw this solution as you mentioned it haha: https://stackoverflow.com/a/19036752/10018602 In my use case, the business day is always 1 for now so I can just do an if statement that checks if the freq value has a B in it, then use this formula. Thanks again! – wildcat89 Jul 25 '22 at 03:50
  • 1
    NP. It looks like [this is the list of supported units for timedelta](https://github.com/pandas-dev/pandas/blob/a62897ae5f5c68360f478bbd5facea231dd55f30/pandas/_libs/tslibs/timedeltas.pyi#L19-L61) (for reference) – Henry Ecker Jul 25 '22 at 03:50

0 Answers0