使用 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 和 calendar 模組。我們使用了“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 開源庫,旨在處理資料操作和分析。它處理由行和列組成的 DataFrame。在 pandas 中,我們有幾個內建方法。其中一些方法是“Timestamp”、“Monthend”、“Dateoff”等。我們可以利用這些方法來處理日期和時間操作。

示例

在下面的示例中,我們首先匯入了 calendar 和 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 的流行庫來處理同一任務。

更新於: 2023年7月18日

1K+ 次檢視

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告