How to Compute the Third‑Last Workday of a Month Using Python
This article shows a step‑by‑step Python solution for finding the third last working day of any month, explaining the logic behind handling month‑end dates and weekend adjustments, and provides ready‑to‑run code for immediate use.
Introduction
In a recent Python discussion, a user asked how to quickly calculate the third last workday of the current month. Existing searches on CSDN and ChatGPT did not yield a satisfactory answer, so a custom solution was developed.
Implementation
Using ChatGPT’s suggestion, the following Python code determines the month’s last day, backs up to the previous workday, and then steps back two more workdays to obtain the third last workday.
import datetime
def get_third_last_workday(year, month):
# Find the last day of the month
last_day = datetime.date(year, month, 1) + datetime.timedelta(days=31)
last_day -= datetime.timedelta(days=last_day.day)
# Move back until a weekday is found
while True:
if last_day.weekday() < 5:
break
last_day -= datetime.timedelta(days=1)
# Step back two more workdays to get the third last workday
third_last_workday = last_day - datetime.timedelta(days=2)
while True:
if third_last_workday.weekday() < 5:
break
third_last_workday -= datetime.timedelta(days=1)
return third_last_workday
# Example
print(get_third_last_workday(2023, 6)) # Output: 2023-06-28The script correctly returns the desired date, demonstrating a practical approach to date arithmetic in Python.
Conclusion
The article presents a clear Python‑based method for solving the “third last workday” problem, offering both the reasoning and a ready‑to‑run code snippet that readers can adapt to their own projects.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
