Python: give start and end of week data from a given date

PythonDateTime

Python Problem Overview


day = "13/Oct/2013"
print("Parsing :",day)
day, mon, yr= day.split("/")
sday = yr+" "+day+" "+mon
myday = time.strptime(sday, '%Y %d %b')
Sstart = yr+" "+time.strftime("%U",myday )+" 0"
Send = yr+" "+time.strftime("%U",myday )+" 6"
startweek = time.strptime(Sstart, '%Y %U %w')
endweek = time.strptime(Send, '%Y %U %w')
print("Start of week:",time.strftime("%a, %d %b %Y",startweek))
print("End of week:",time.strftime("%a, %d %b %Y",endweek))
print("Data entered:",time.strftime("%a, %d %b %Y",myday))

out:
Parsing : 13/Oct/2013
Start of week: Sun, 13 Oct 2013
End of week: Sat, 19 Oct 2013
Sun, 13 Oct 2013

Learned python in the past 2 days and was wondering if there is a cleaner way to do this.This method works...it just looks ugly and It seems silly to have to create a new time variable for each date, and that there should be a way to offset the given date to the start and end of the week through a simple call but i have been unable to find anything on the internet or documentation that looks like it would work.

Python Solutions


Solution 1 - Python

Use the datetime module.

This will yield start and end of week (from Monday to Sunday):

from datetime import datetime, timedelta

day = '12/Oct/2013'
dt = datetime.strptime(day, '%d/%b/%Y')
start = dt - timedelta(days=dt.weekday())
end = start + timedelta(days=6)
print(start)
print(end)

EDIT:

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

Solution 2 - Python

Slight variation if you want to keep the standard time formatting and refer to the current day:

from datetime import date, timedelta

today = date.today()
start = today - timedelta(days=today.weekday())
end = start + timedelta(days=6)
print("Today: " + str(today))
print("Start: " + str(start))
print("End: " + str(end))

Solution 3 - Python

Use the pendulum module:

today = pendulum.now()
start = today.start_of('week')
end = today.end_of('week')

Solution 4 - Python

you can also use Arrow:

import arrow
now = arrow.now()
start_of_week = now.floor('week')
end_of_week = now.ceil('week')

Solution 5 - Python

pip install pendulum

import pendulum
 
today = pendulum.now()
 
start = today.start_of('week')
print(start.to_datetime_string())
 
end = today.end_of('week')
print(end.to_datetime_string())

found from here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionshadowtdt09View Question on Stackoverflow
Solution 1 - PythonHyperboreusView Answer on Stackoverflow
Solution 2 - PythonpalamunderView Answer on Stackoverflow
Solution 3 - PythonogeretalView Answer on Stackoverflow
Solution 4 - PythonAlon GouldmanView Answer on Stackoverflow
Solution 5 - PythonHinal PatelView Answer on Stackoverflow