0

Sunday is first day the week.

E.g. Today is Saturday, 9th of Feb 2019. I want the date of first day of that week which is 3rd of Feb 2019. How can I do that in Python 3?

Also if today is 7th Feb 2019 which is Thursday, and the first of day of that week is also 3rd Feb 2019.

How can I do that in Python 3?

Thank you

smileymike
  • 253
  • 6
  • 22
  • There are multiple ways to do this. What work have you done on this problem so far, and just where are you stuck? By the way, what are the possible years that may be input? Do you want the Gregorian calendar? What modules are allowed to be used--`datetime` or perhaps a third-party module? – Rory Daulton Feb 09 '19 at 19:12
  • 4th of Feb 2019 is a Monday. – Mark Feb 09 '19 at 19:16
  • Mark, well spot, it should be 3rd of Feb 2019 as on Sunday. I am frustrated and wondering if there is elegant solution. I use datetime.date.today() – smileymike Feb 09 '19 at 19:33

1 Answers1

2

You will want to use the datetime module.

This will yield start of the week:

from datetime import datetime, timedelta

day = '09/Feb/2019'
dt = datetime.strptime(day, '%d/%b/%Y')
start = dt - timedelta(days=dt.weekday()+1)

print(start.strftime('%d/%b/%Y'))

Answer above modified from this answer on a similar question. The datetime module is your friend!

devdyl
  • 41
  • 1
  • 5
  • The 4th of Feb is a Monday because the return value of `weekday` is indexed starting on Monday. – Mark Feb 09 '19 at 19:21
  • Good catch @MarkMeyer, edited answer above to correct answer. I appended "+1" to the end of the weekend() function call. – devdyl Feb 09 '19 at 19:26
  • Yeah, that now gives a Sunday, although it seems a little weird that if you start on a Sunday you don't get the same day back. – Mark Feb 09 '19 at 19:27
  • Hm, you're right. A quick conditional check to see if the inputted date is a Sunday could work. There is probably a more elegant solution, however. – devdyl Feb 09 '19 at 19:39