5 Best Ways to Determine Last Friday’s Date Using Python

πŸ’‘ Problem Formulation: When working with dates in Python, a common task may be to find out the date of the last Friday. For example, if today is Wednesday, March 15, 2023, the input would be today’s date and the desired output would be Friday, March 10, 2023.

Method 1: Using datetime and timedelta

This method involves the datetime module, which is part of the standard Python library. The idea is to subtract a timedelta object from the current date until we reach the most recent Friday. The weekday() function is used to get the current day of the week as an integer, where Monday is 0 and Sunday is 6.

Here’s an example:

from datetime import datetime, timedelta

def last_friday():
    today = datetime.today()
    offset = (today.weekday() - 4) % 7
    last_friday_date = today - timedelta(days=offset)
    return last_friday_date

print(last_friday())

The output will be:

2023-03-10 00:00:00

This code snippet defines a function last_friday() that calculates the last Friday relative to the current day. It uses datetime.today() to get the current date and then calculates the offset to last Friday. It returns the date of the last Friday without the time component.

Method 2: Using pandas

Pandas is a powerful data manipulation library that provides convenient functionalities to work with date and time data. The Timestamp and DateOffset classes can be used to handle dates in a more intuitive manner, especially for those familiar with pandas.

Here’s an example:

import pandas as pd

def last_friday():
    today = pd.to_datetime('today')
    last_friday_date = today - pd.DateOffset(days=(today.dayofweek - 4) % 7)
    return last_friday_date

print(last_friday())

The output will be:

2023-03-10 00:00:00

The code defines a function last_friday() using pandas to manage date calculations. pd.to_datetime('today') captures the current date, while pd.DateOffset is used to find the last Friday date. It’s a concise method for those who already use pandas, though it introduces an external dependency.

Method 3: Using numpy

Numpy, a library mainly used for numerical operations, also provides support for date and time types. The numpy library can perform vectorized operations on dates, which can be handy if we’re looking to calculate this for an array of dates.

Here’s an example:

import numpy as np

def last_friday():
    today = np.datetime64('today')
    last_friday_date = today - np.timedelta64((today.astype('datetime64[D]').view(int) - 4) % 7, 'D')
    return last_friday_date

print(last_friday())

The output will be:

2023-03-10

This code example defines a function last_friday() that uses Numpy’s datetime64 and timedelta64 to calculate the date of the last Friday. The approach is similar to that of the datetime module but leverages numpy’s array operations, which can be very efficient.

Method 4: Using dateutil

The dateutil library is a powerful extension to the standard datetime module. It provides additional functionality for calculating relative deltas and working with recurring events using the rrule utility.

Here’s an example:

from datetime import datetime
from dateutil.relativedelta import relativedelta, FR

def last_friday():
    today = datetime.now()
    last_friday_date = today + relativedelta(weekday=FR(-1))
    return last_friday_date

print(last_friday())

The output will be:

2023-03-10 00:00:00

The example shows a function last_friday() that calculates the date of the last Friday using the dateutil module. The relativedelta function is particularly useful, as it allows to specify which day of the week to move to while also allowing to indicate how many weeks back one wants to go.

Bonus One-Liner Method 5: Using calendar and datetime modules

This one-liner combines the standard library calendar and datetime modules to quickly determine the date of the last Friday. It’s a neat trick that is concise and requires no external dependencies.

Here’s an example:

from datetime import datetime, timedelta
import calendar

last_friday_date = (datetime.today() - timedelta(days=(datetime.today().weekday() + (7 - calendar.FRIDAY)) % 7))
print(last_friday_date)

The output will be:

2023-03-10 00:00:00

This snippet calculates the last Friday’s date in a single line of code. It uses the modulo operation to find the correct number of days to subtract from the current date and FRIDAY from the calendar module to ensure readability.

Summary/Discussion

  • Method 1: Datetime and Timedelta. Simple. Uses standard library.
  • Method 2: Pandas. Convenient for pandas users. Adds an external dependency.
  • Method 3: Numpy. Good for array operations. Requires familiarity with numpy.
  • Method 4: Dateutil. Powerful date calculations. External library needed.
  • Bonus Method 5: Calendar and Datetime. Concise one-liner. Relies on standard libraries.