python - 将 pandas 偏移量转换为 python 日期

标签 python pandas

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/

相关文章:

python - 如何在 numpy 中将 int 值更改/重新映射到 str

python - 如何计算三只股票的加权平均数

python - 缺少 key 的 Pandas groupby

python - pandas groupby 中连续日期之间的差异

python - 无法导入 Pandas 和 numpy

python - 在 python 中运行的脚本中关闭 GPU

python - 使用其顶点绘制三角形并使用plotly python 填充 3D 空间中的形状

python - matplotlib boxplot xticks 向 y 轴移动

python - 如何对 Selenium Python 中的 table/tbody 中找到的每个元素执行 click() ?

python - 根据 Pandas python 中的两个条件选择数据框的行