[Rod Stephens Books]
Index Books Python Examples About Rod Contact
[Mastodon] [Bluesky]
[Build Your Own Ray Tracer With Python]

[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

Title: Find the Friday after a given date in Python

[The program finding the following Friday]

The following find_friday function returns the next Friday on or after a given date.

The code first gets the date's week day. The datetime class starts numbering dates with Monday = 0, so Friday's weekday value is 4.

The code subtracts 4 from that value to get the number of days between the date and Friday.

If the date is between Monday and Thursday, then the difference is positive and gives the number of days until the next Friday. If the date is a Saturday or Sunday, then the difference is negative and gives the number of days to the previous Friday. If the difference is 0, then the date is a Friday.

To get the date of the next Friday, the code adds 7 and takes the result modulo 7 to get a value in the range 0 to 6. It converts that number of days into a timedelta and adds it to the date to get the next Friday.

import datetime def find_friday(date): return date + datetime.timedelta((4 - date.weekday()) % 7)

The program uses the following code to test the function.

import datetime for day in range(1, 10): date = datetime.datetime(2024, 11, day) friday = find_friday(date) week_day = f'{date:%A}.' print(f'{date:%m/%d/%y} is a {week_day:10} The next Friday is {friday:%A} {friday:%m/%d/%y}')

This code loops through day numbers 1 through 9, creates the date 11/<day_number>/2024, passes it into the find_friday function, and displays the result.

Here are the results:

11/01/24 is a Friday. The next Friday is Friday 11/01/24 11/02/24 is a Saturday. The next Friday is Friday 11/08/24 11/03/24 is a Sunday. The next Friday is Friday 11/08/24 11/04/24 is a Monday. The next Friday is Friday 11/08/24 11/05/24 is a Tuesday. The next Friday is Friday 11/08/24 11/06/24 is a Wednesday. The next Friday is Friday 11/08/24 11/07/24 is a Thursday. The next Friday is Friday 11/08/24 11/08/24 is a Friday. The next Friday is Friday 11/08/24 11/09/24 is a Saturday. The next Friday is Friday 11/15/24

Download the example to see additional details.

© 2024 - 2025 Rocky Mountain Computer Consulting, Inc. All rights reserved.