Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Current week in Python?

good morning, I’m in the middle of a project and I’m stuck on finding a way to return every day of the current week in a list. It would be something like this:

week=[ '2022-06-07' , '2022-06-08' , '2022-06-09' , '' , '...']

I would be very grateful if you could explain to me a way to obtain this result,,, thanks

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can shorten this but I wrote it out like this for clarity.

from datetime import datetime, timedelta

date_obj = datetime(2022, 6, 7)  # Today, Tuesday
monday = date_obj - timedelta(days=date_obj.weekday())  # assuming start of week is Monday
week = []
for i in range(7):
    week.append((monday + timedelta(days=i)).strftime("%Y-%m-%d"))
print(week)

Output:

# Monday 6/6 to Sunday 6/12
['2022-06-06', '2022-06-07', '2022-06-08', '2022-06-09', '2022-06-10', '2022-06-11', '2022-06-12']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading