【问题标题】:How to get quarter beginning date in python如何在python中获取季度开始日期
【发布时间】:2019-04-10 18:18:51
【问题描述】:

我想获取日期季度的开始日期

x="2018-02-07"
x=pd.to_datetime(x)
x=x-pd.offsets.QuarterBegin()
print(x)
2017-12-01 00:00:00

这是错误的,应该是“2018-01-01 00:00:00

谁能帮我解决我哪里出错了?

【问题讨论】:

    标签: python python-3.x pandas date datetime


    【解决方案1】:

    您可以先转换为句点,然后再转换为时间戳:

    x = pd.to_datetime('2018-02-07')
    
    res = x.to_period('Q').to_timestamp()
    
    print(res)
    
    Timestamp('2018-01-01 00:00:00')
    

    【讨论】:

      【解决方案2】:

      在不依赖 Pandas 的核心 Python 中:

      from datetime import date
      
      
      x = date.fromisoformat('2018-02-07')
      x_qtr = date(x.year, 3 * ((x.month - 1) // 3) + 1, 1)
      
      print(x_qtr)
      # 2018-01-01
      

      【讨论】:

        【解决方案3】:
        pd.to_datetime("2018-02-07") - pd.tseries.offsets.BQuarterBegin(startingMonth=1)
        

        【讨论】:

          猜你喜欢
          • 2019-08-07
          • 2014-02-06
          • 1970-01-01
          • 2018-12-28
          • 1970-01-01
          • 1970-01-01
          • 2021-12-29
          • 2016-05-05
          • 1970-01-01
          相关资源
          最近更新 更多