【问题标题】:Convert pandas offset to python date将熊猫偏移量转换为 python 日期
【发布时间】:2017-05-11 19:58:02
【问题描述】:

Pandas 在 pandas.tseries.frequency 包中有方便的方法 to_offset,它将字符串转换为偏移量:

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

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    如果需要使用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
    

    【讨论】:

      【解决方案2】:
      In [149]: pd.datetime.today() - pd.DateOffset(days=10)
      Out[149]: Timestamp('2017-05-01 13:44:38.082351')
      

      你也可以截断时间:

      In [154]: (pd.datetime.today() - pd.DateOffset(days=10)).normalize()
      Out[154]: Timestamp('2017-05-01 00:00:00')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-20
        • 1970-01-01
        • 2021-09-16
        • 2015-09-19
        • 2017-03-05
        • 2018-08-09
        • 1970-01-01
        • 2018-09-23
        相关资源
        最近更新 更多