'pd.to_timedelta('1D') works while pd.to_timedelta('D') fails. Issue when converting ferquency to timedelta

I'm encountering a silly problem I guess.

Currently, I'm using pd.infer_freq to get the frequency of a dataframe index. Afterwards, I use pd.to_timedelta() to convert this frequency to a timedelta object, to be added to another date.

This works quite fine, except when the dataframe index has a frequency which can be expressed as a single time unit (eg. 1 day, or 1 minute).

To be more precise,

freq = pd.infer_freq(df)
# let's say it gives '2D' because data index is spaced on that interval
timedelta = pd.to_timedelta(freq) 

works, while

freq = pd.infer_freq(df)
# let's say it gives 'D' because data index is spaced on that interval
timedelta = pd.to_timedelta(freq) 

fails and returns

ValueError: unit abbreviation w/o a number

This could work if I supplied '1D' instead of 'D' though. I could try to check if the first character of the freq string is numeric, and add '1' otherwise, but that seems quite cumbersome.

Is anyone aware of a better approach ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source