Pandas 有一个方便的方法 to_offset,在包 pandas.tseries.frequency 中,它将字符串转换为偏移量:
from pandas.tseries.frequencies import to_offset
_30_days_ago = to_offset("30D")
如何将偏移量转换为:
- 一个 Python 日期,或者
- 格式为
yyyy-mm-dd
的字符串
特别是,如何使用偏移量来计算日期?例如,如果今天是 2017-05-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'>
对于字符串添加 strftime
:
ts_str = ts.strftime('%Y-%m-%d')
print (ts_str)
2017-05-01
print (type(ts_str))
<class 'str'>
并为日期添加 date()
:
ts_python_date = ts.date()
print (ts_python_date)
2017-05-01
print (type(ts_python_date))
<class 'datetime.date'>
另一个解决方案是使用 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
关于python - 将 pandas 偏移量转换为 python 日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43914460/