Last active
March 2, 2024 06:39
-
-
Save igniteflow/e8402958c92f8a84c58e5e8eb13e262a to your computer and use it in GitHub Desktop.
Print the number of business days and weekend days in a month
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
""" | |
Print the number of business days and weekend days in a month | |
Example usage: | |
$ python ./business-days-in-month.py 2024 2 | |
February, 2024 has 21 weekdays and 8 weekend days | |
Optional: Make the script executable | |
$ chmod +x ./business-days-in-month.py | |
$ ./business-days-in-month.py 2024 2 | |
""" | |
import argparse | |
import calendar | |
import datetime | |
from collections import defaultdict | |
WEEKDAYS = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday") | |
def main(year, month): | |
days_in_month = calendar.monthrange(year, month)[1] | |
days = defaultdict(list) | |
for i in range(1, days_in_month + 1): | |
day = datetime.date(year, month, i) | |
key = "weekdays" if day.strftime("%A") in WEEKDAYS else "weekends" | |
days[key].append(day) | |
month_yr_str = datetime.date(year, month, 1).strftime("%B, %Y") | |
num_weekdays = len(days["weekdays"]) | |
num_weekend_days = len(days["weekends"]) | |
assert num_weekdays + num_weekend_days == days_in_month | |
print( | |
f"{month_yr_str} has {num_weekdays} weekdays and {num_weekend_days} weekend days for a total of {days_in_month} days." | |
) | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser( | |
description="Print the number of business days and weekend days in a month" | |
) | |
parser.add_argument("year", type=int, help="Year (YYYY)") | |
parser.add_argument("month", type=int, help="Month (1-12)") | |
args = parser.parse_args() | |
main(args.year, args.month) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment