Convoxity
Convoxity

Reputation: 37

Get current date if day is weekday, else get date of most recent weekday (i.e., Friday)

Can anyone think of an elegant one liner for this?

My attempt:

dt.datetime.today() if dt.datetime.today().isoweekday() in range(1, 6) else 'date of last friday?'

Upvotes: 0

Views: 1168

Answers (1)

Deepstop
Deepstop

Reputation: 3827

I would prefer two lines, although 1 is possible. The reason is if you call dt.datetime.today() twice there is a (very small) chance that you get two different answers, if it is run a split second before midnight. Also it is probably more efficient to store the value than call the function twice.

import datetime as dt

thisday = dt.datetime.today().date()
thisday -= dt.timedelta(days=max(0,thisday.weekday()-4,0))

On saturday weekday() returns 5, on Sunday it returns 6, so we subtract 1 or 2 days respectively. On other days, weekday() - 4 is zero or less, so the max function returns zero and nothing is subtracted.

Upvotes: 1

Related Questions