Skip to content

Commit

Permalink
fix: Add code to calculate days excluding weekends | utility.py
Browse files Browse the repository at this point in the history
  • Loading branch information
sejungkwak committed Jun 4, 2022
1 parent edb60ae commit 55ef15f
Showing 1 changed file with 38 additions and 10 deletions.
48 changes: 38 additions & 10 deletions worktime/app/utility.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,32 @@ def clear():


def get_current_datetime():
"""Return the current date and time in Dublin in a dictionary."""
"""Get the current datetime of Dublin.
Returns:
dict: The current year, date and time of Dublin.
"""
DUBLIN = pytz.timezone("Europe/Dublin")
now = datetime.now(DUBLIN)
date = now.date().strftime("%d/%m/%Y")
time = now.time().strftime("%H:%M:%S")
return {"year": now.year, "date": date, "time": time}


def get_week(data, result):
def get_week(xdate, result):
"""Return a list of a week(inc./excl. weekend) of the given date.
Args:
:data class: An instance of datetime.date.
:result str: Including or excluding weekend
:xdate class: An instance of datetime.date().
:result str: Including or excluding weekend.
Returns
list: Dates of a week.
"""
# Source: ALFAFA's answer on Stack Overflow
# https://stackoverflow.com/questions/56163008
week = data.isocalendar()[2]
start = data - timedelta(days=week)
week = xdate.isocalendar()[2]
start = xdate - timedelta(days=week)
dates = []
if result == "weekdays":
for day in range(1, 6):
Expand All @@ -42,14 +49,35 @@ def get_week(data, result):
return dates


def convert_date(data):
"""Convert a date to an instance of datetime.date.
def convert_date(xdate):
"""Split a string into a list of integers that represet
year, month and date, and then pass them to date().
Args:
:data str: A day/month/year formatted date.
:xdate str: A day/month/year formatted date.
Returns:
class: A instans of datetime.date().
"""
date_to_list = data.split("/")
date_to_list = xdate.split("/")
year = int(date_to_list[2])
month = int(date_to_list[1])
day = int(date_to_list[0])
return date(year, month, day)


def get_num_of_weekdays(date1, date2):
"""Calculate total number of weekdays between two dates.
Args:
:date1: Start date.
:date2: End date.
Returns:
int: Total number of weekdays.
"""
# Source: Dave Webb's answer on Stack Overflow
# https://stackoverflow.com/questions/3615375
days = (date1 + timedelta(n) for n in range((date2 - date1).days + 1))
total_weekdays = sum(1 for day in days if day.weekday() < 5)
return total_weekdays

0 comments on commit 55ef15f

Please sign in to comment.