0

I would like to have a function get_cw_borders(year: int, cw: int) -> Tuple[datetime.datetime, datetime.datetime] which should behave like this:

>>> get_cw_borders(2020, 17)
(datetime.datetime(2020, 4, 20), datetime.datetime(2020, 4, 26))

>>> get_cw_borders(2020, 18)
(datetime.datetime(2020, 4, 27), datetime.datetime(2020, 5, 3))

>>> get_cw_borders(2020, 1)
(datetime.datetime(2019, 12, 30), datetime.datetime(2020, 1, 5))

>>> get_cw_borders(2017, 1)
(datetime.datetime(2017, 1, 2), datetime.datetime(2017, 1, 8))

I'm aware that some countries start the week on Sunday instead of Monday. I think (please correct me if I'm wrong) that this is just a constant offset for this function, so that would not be a big deal.

Is there a built-in function to get this?

Non-Duplicates

Thank you for linking similar questions.

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958

2 Answers2

0

You can either use the method described in this answer or you can use a 3rd party package like arrow to achieve it a bit more easily with the following:

import arrow

today = arrow.utcnow()

print(f'{today:YYYY-MM-DD}')
print(f'{today.ceil("week"):YYYY-MM-DD}')
print(f'{today.floor("week"):YYYY-MM-DD}')

Output:

2020-06-02
2020-06-07
2020-06-01

Using span instead of floor and ceil will give you the tuple:

print(f'{today.span("week")}')
>>> (<Arrow [2020-06-01T00:00:00+00:00]>, <Arrow [2020-06-07T23:59:59.999999+00:00]>)
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dror Av.
  • 1,184
  • 5
  • 14
0

datetime.strptime supports week number and week day in the format. Note that the week day is required, but you can do something like:

def get_cw_borders(week_number):
    start = datetime.strptime(f"2020-{week_number}-0", "%Y-%U-%w")
    end = datetime.strptime(f"2020-{week_number}-6", "%Y-%U-%w")
    return (start, end)

Note that %U and %w consider sunday as the first day of the week. If you want the week to start on monday, you can use %W, but need some extra work to make the week day work.

I think you can do the following when starting the week on monday:

def get_cw_borders_start_on_monday(week_number):
    # Week day 1 indicates monday
    start = datetime.strptime(f"2020-{week_number}-1", "%Y-%W-%w")
    # Week day 0 indicates sunday, at end of week when using %W
    end = datetime.strptime(f"2020-{week_number}-0", "%Y-%W-%w")
    return (start, end)
b9s
  • 517
  • 4
  • 13