Pandas在软件包pandas.tseries.frequency中具有方便的方法to_offset,该方法将字符串转换为偏移量:
from pandas.tseries.frequencies import to_offset
_30_days_ago = to_offset("30D")
Run Code Online (Sandbox Code Playgroud)
如何将偏移量转换为:
yyyy-mm-dd特别是,如何使用偏移量来计算日期?例如,如果今天是2017年5月11日,如何使用to_offset("10D")该日期2017-05-01?
如果需要使用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'>
Run Code Online (Sandbox Code Playgroud)
对于字符串,请添加strftime:
ts_str = ts.strftime('%Y-%m-%d')
print (ts_str)
2017-05-01
print (type(ts_str))
<class 'str'>
Run Code Online (Sandbox Code Playgroud)
对于日期,请添加date():
ts_python_date = ts.date()
print (ts_python_date)
2017-05-01
print (type(ts_python_date))
<class 'datetime.date'>
Run Code Online (Sandbox Code Playgroud)
另一个解决方案是使用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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
331 次 |
| 最近记录: |