Skip to content

Instantly share code, notes, and snippets.

@yeiichi
Created December 15, 2024 00:22
Show Gist options
  • Save yeiichi/cf6e8e8f32ef6caf723f7805dd03d662 to your computer and use it in GitHub Desktop.
Save yeiichi/cf6e8e8f32ef6caf723f7805dd03d662 to your computer and use it in GitHub Desktop.
Return the dates within the same week as the given date.
#!/usr/bin/env python3
from collections import namedtuple
from datetime import datetime
def get_week_dates(date_str):
"""Return the dates within the same week as the given date.
Args:
date_str (str): A date string in ISO format (e.g., '2021-01-01').
Returns:
list: A list of `DateAttrs` namedtuples, where each tuple includes the
following attributes for a day in the specified ISO week:
- year: Year of the date.
- week: ISO week number corresponding to the date.
- month: Month of the date.
- day: Day of the date.
- day_of_week: Name of the day of the week (e.g., 'Mon', 'Tue').
"""
base_date = datetime.fromisoformat(date_str).isocalendar()
DateAttrs = namedtuple('DateAttrs', 'year week month day day_of_week')
dates = []
for i in range(1, 8):
each_date = datetime.fromisocalendar(base_date[0], base_date[1], i).date()
dates.append(
DateAttrs(
each_date.year,
base_date[1], # ISO week number
each_date.month,
each_date.day,
each_date.strftime('%a')
)
)
return dates
def date_str_from_stdin():
date_input = input('Date? (yyyy-mm-dd or RETURN for today) >> ')
my_date = str(datetime.now().date()) if date_input == '' else date_input
return get_week_dates(my_date)
if __name__ == '__main__':
dates_ = date_str_from_stdin()
for date_ in dates_:
print(date_)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment