【问题标题】:How to get previous 2 and 3 months end date in python如何在python中获取前2个月和3个月的结束日期
【发布时间】:2021-05-20 20:02:13
【问题描述】:

我正在尝试获取前 2 个月和 3 个月的结束日期。在下面的代码中,我可以获得最后一个月的结束日期,即 2021-01-31,但我还需要获得 2020-12-31 和 2020-11-30。

非常感谢任何建议。

today = datetime.date.today()
first = today.replace(day=1)
lastMonth = first - dt.timedelta(days=1)
date1=lastMonth.strftime("%Y-%m-%d")
date1

输出[90]:'2021-01-31'

【问题讨论】:

  • 这里实际上是在使用 pandas 还是只是原生 python datetime 库?
  • "任何建议都非常感谢",但您没有费心对所提供的 4 个答案中的任何一个都投一票吗?
  • 如何投票?
  • 想出了如何投票。刚刚做了。

标签: python python-3.x pandas datetime


【解决方案1】:

无需处理每个月不同天数的快速而肮脏的方法是简单地重复该过程 N 次,其中 N 是您想要的月数:

import datetime

today = datetime.date.today()
temp_date = today.replace(day=1)
for _ in range(3):
    previous_month = temp_date - datetime.timedelta(days=1)
    print(previous_month.strftime("%Y-%m-%d"))
    temp_date = previous_month.replace(day=1)

输出

2021-01-31
2020-12-31
2020-11-30

【讨论】:

    【解决方案2】:

    你可以使用日历包:

    import calendar
    calendar.monthrange(2020, 2)[1] # gives you the last day of Feb 2020
    

    【讨论】:

      【解决方案3】:

      试试:

      prev2month = lastMonth - pd.offsets.MonthEnd(n=1)
      
      prev3month = lastMonth - pd.offsets.MonthEnd(n=2)
      

      offset的更多使用信息(例如MonthEndMonthBegin)可以在documentation中找到。

      【讨论】:

        【解决方案4】:

        如果你确定使用,那么你可以使用date_range,例如:

        pd.date_range('today', periods=4, freq='-1M', normalize=True)
        

        这会给你:

        DatetimeIndex(['2021-02-28', '2021-01-31', '2020-12-31', '2020-11-30'], dtype='datetime64[ns]', freq='-1M')
        

        忽略第一个元素并根据需要使用...

        或者:

        dr = pd.date_range(end='today', periods=3, freq='M', normalize=True)[::-1]
        

        这给了你:

        DatetimeIndex(['2021-01-31', '2020-12-31', '2020-11-30'], dtype='datetime64[ns]', freq='-1M')
        

        如果你想要字符串,你可以使用dr.strftime('%Y-%m-%d'),它会给你Index(['2021-01-31', '2020-12-31', '2020-11-30'], dtype='object')

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-09-30
          • 1970-01-01
          • 2012-10-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多