【问题标题】:How to get the first and last date of the month with Year and Month in python如何在python中使用年份和月份获取月份的第一个和最后一个日期
【发布时间】:2021-12-30 11:25:11
【问题描述】:

在下面的代码中,从月份和年份开始,需要每月的第一个和最后一个日期

对于前一个月 =3 和年份 = 2022

first_date = 2021-03-01 00:00:00

last_date = 2021-03-31 00:00:00

我尝试使用日历,但它只是返回 (1 ,31)

import calendar

month =3
year= 2022
print( calendar.monthrange(2002, 1))

【问题讨论】:

  • 您可能希望使用已定义的变量(monthyear),而不是打印不同月份和年份的范围。您将返回指定月份的最低和最高天数,因此您现在只需将它们转换为 datetime 对象(使用 datetime.datetime(year, month, day))。

标签: python python-3.x


【解决方案1】:

从monthrange() 中,您将获得该月的第一天和天数。您可以使用 datetime 方法将其转换为日期。

month =3
year= 2022
first, last = calendar.monthrange(year, month)
print(first, last)

print(datetime.datetime(year, month, 1))
print(datetime.datetime(year, month, last))

【讨论】:

    【解决方案2】:

    您可以编写自己的函数来计算当月的最后一天:

    def last_day_of_month(date):
        if date.month == 12:
            return date.replace(day=31)
        return date.replace(month=date.month+1, day=1) - datetime.timedelta(days=1)
    

    所以:

    >>> last_day_of_month(datetime.date(2021, 3, 19))
    datetime.date(2021, 3, 31)
    

    同样,我们可以在第一次约会时使用单线:

    (dt.replace(day=1) + datetime.timedelta(days=32)).replace(day=1)
    

    所以:

    dt = datetime.datetime(2021, 3, 19)
    print((dt.replace(day=1) + datetime.timedelta(days=32)).replace(day=1))
    >>> 2021-03-01 00:00:00
    

    【讨论】:

      【解决方案3】:

      您可以使用datetime 模块完成此操作

      import datetime
      
      def get_last_day_of_month(day):
          next_month = day.replace(day=28) + datetime.timedelta(days=4)
          return next_month - datetime.timedelta(days=next_month.day)
      

      输出将是:

      for month in range(1, 13):
          print(get_last_day_of_month(datetime.date(2020, month, 1)))
      
          
      2020-01-31
      2020-02-29
      2020-03-31
      2020-04-30
      2020-05-31
      2020-06-30
      2020-07-31
      2020-08-31
      2020-09-30
      2020-10-31
      2020-11-30
      2020-12-31
      

      对于第一天,您可以将日期始终设置为 1

      【讨论】:

        猜你喜欢
        • 2021-12-07
        • 1970-01-01
        • 1970-01-01
        • 2014-06-26
        • 2013-01-06
        • 2021-12-16
        • 2016-06-17
        • 2014-11-21
        • 1970-01-01
        相关资源
        最近更新 更多