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:
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
?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With