Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert pandas offset to python date

Tags:

python

pandas

Pandas has the handy method to_offset, in package pandas.tseries.frequency, which converts a string to an offset:

from pandas.tseries.frequencies import to_offset
_30_days_ago = to_offset("30D")

How can I convert from an offset to:

  • a Python date, or
  • a string in format yyyy-mm-dd

In particular, how can I use offset to calculate dates? For example, if today is 2017-05-11, how can I use to_offset("10D") to get the date 2017-05-01 ?

like image 796
Leonel Avatar asked Mar 10 '23 02:03

Leonel


1 Answers

If need use to_offset:

from pandas.tseries.frequencies import to_offset

ts = pd.to_datetime('2017-05-11') - to_offset("10D")
print (ts)
2017-05-01 00:00:00

print (type(ts))
<class 'pandas._libs.tslib.Timestamp'>

For string add strftime:

ts_str = ts.strftime('%Y-%m-%d')
print (ts_str)
2017-05-01
print (type(ts_str))
<class 'str'>

And for date add date():

ts_python_date = ts.date()
print (ts_python_date)
2017-05-01
print (type(ts_python_date))
<class 'datetime.date'>

Another solution is use Timedelta:

print (pd.to_datetime('2017-05-11') - pd.Timedelta('10D'))
#same as
#print ((pd.to_datetime('2017-05-11') - pd.to_timedelta('10D')))
2017-05-01 00:00:00
like image 189
jezrael Avatar answered Mar 21 '23 08:03

jezrael