使用 Python 查找一年中每个月的最后一个工作日
工作日在企业部门被称为工作日,在某些部门是周一至周五,在某些部门是周一至周六。在本文中,我们将了解如何使用 Python 查找每年的最后一个工作日。Python 提供了各种库,如 datetime、time、calendar 等来处理时间操作。我们将利用这些库来编写相同的程序。此外,一些库(如 Pandas)也有内置方法来支持此类时间操作。
使用 Datetime 和 Calender 模块
"datetime"和"calendar"是处理时间的标准 Python 模块。它提供了几个实用函数来处理时间数据。工作日的定义可能因多种因素而异。通常,周一至周五被视为工作日。
示例
在下面的例子中,我们使用"monthrange"方法来确定给定月份的天数。另一方面,"datetime.date"方法创建一个日期对象来处理时间操作。接下来,我们使用一个 while 循环不断将"date"减少一天,直到遇到任何工作日(从星期一到星期五)。最后我们返回了"date"对象。
import datetime import calendar def last_business_day(year, month): last_day = calendar.monthrange(year, month)[1] date = datetime.date(year, month, last_day) while date.weekday() > 4: date -= datetime.timedelta(days=1) return date year = 2023 month = 9 last_bd = last_business_day(year, month) print("The last business day of {} {} is {}.".format( calendar.month_name[month], year, last_bd))
输出
The last business day of September 2023 is 2023-09-29.
使用 Dateutils 库
Python 的"dateutil"库提供了多种功能,这些功能超出了 Python 的"datetime"库。它包含"rrule"模块,允许我们使用循环日期。这在数据处理、生成日期序列等方面具有广泛的应用。另一方面,"relativedelta"类允许我们对日期时间执行加法、减法等操作。
示例
在下面的例子中,我们使用了 datetime 、dateutils 和日历模块。我们使用"dateutil"模块的"rrule"方法来生成要求每月生成的循环规则。我们使用"byweekly"参数指定要考虑的日期为周一至周五。我们保留"count=1"以仅获取一个日期元素。
import datetime from dateutil import rrule, relativedelta import calendar def last_business_day(year, month): rule = rrule.rrule( rrule.MONTHLY, bymonth=month, bysetpos=-1, byweekday=(rrule.MO, rrule.TU, rrule.WE, rrule.TH, rrule.FR), dtstart=datetime.datetime(year, month, 1), count=1 ) return rule[0].date() year = 2023 month = 4 last_bd = last_business_day(year, month) print("The last business day of {} {} is {}.".format( calendar.month_name[month], year, last_bd))
输出
The last business day of April 2023 is 2023-04-28.
使用 Pandas 库
Pandas 是一个流行的 Python 开源库,用于处理数据操作和分析。它处理由行和列组成的数据框。在 Pandas 中,我们有几种内置方法。其中一些方法是"Timestamp"、"Monthend"、"Dateoff"等。我们可以利用这些方法来处理日期和时间操作。
示例
在下面的例子中,我们首先导入了日历和 Pandas 库。我们使用"Timestamp"方法创建日期时间对象,使用"Monthend"方法获取当月的最后日期。接下来,我们检查日期是否属于工作日类别。如果不是,我们继续将日期减一,直到找到属于工作日的日期。
import calendar import pandas as pd def last_business_day(year, month): date = pd.Timestamp(year, month, 1) + pd.offsets.MonthEnd(0) while date.weekday() > 4: date -= pd.DateOffset(days=1) return date.date() year = 2023 month = 12 last_bd = last_business_day(year, month) print("The last business day of {} {} is {}.".format( calendar.month_name[month], year, last_bd))
输出
The last business day of December 2023 is 2023-12-29.
结论
在本文中,我们了解了如何使用 Python 查找一年中每个月的最后一个工作日。我们利用 datetime、calendar 库来执行相同的操作。我们使用了多个实用函数,如 Timestamp、rrule 等。我们还看到了另一个名为 Pandas 的流行库的用法来处理相同的任务。