Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last Friday?

The code below should return last Friday, 16:00:00. But it returns Friday of previous week. How to fix that?

now = datetime.datetime.now()
test = (now - datetime.timedelta(days=now.weekday()) + timedelta(days=4, weeks=-1))
test = test.replace(hour=16,minute=0,second=0,microsecond=0)

Upd. I use the following approach now - is it the best one?

now = datetime.datetime.now()
if datetime.datetime.now().weekday() > 4:
    test = (now - datetime.timedelta(days=now.weekday()) + timedelta(days=4))
else:
    test = (now - datetime.timedelta(days=now.weekday()) + timedelta(days=4, weeks=-1))
test = test.replace(hour=16,minute=0,second=0,microsecond=0)

Upd2. Just to give an example. Let's assume that today is Oct 5, 2012. In case current time is equal to or less than 16:00 it should return Sep 28, 2012, otherwise - Oct 5, 2012.

like image 433
LA_ Avatar asked Oct 02 '12 08:10

LA_


4 Answers

The dateutil library is great for things like this:

>>> from datetime import datetime
>>> from dateutil.relativedelta import relativedelta, FR
>>> datetime.now() + relativedelta(weekday=FR(-1))
datetime.datetime(2012, 9, 28, 9, 42, 48, 156867)
like image 78
Jon Clements Avatar answered Oct 16 '22 08:10

Jon Clements


As in the linked question, you need to use datetime.date objects instead of datetime.datetime. To get a datetime.datetime in the end, you can use datetime.datetime.combine():

import datetime

current_time = datetime.datetime.now()

# get friday, one week ago, at 16 o'clock
last_friday = (current_time.date()
    - datetime.timedelta(days=current_time.weekday())
    + datetime.timedelta(days=4, weeks=-1))
last_friday_at_16 = datetime.datetime.combine(last_friday, datetime.time(16))

# if today is also friday, and after 16 o'clock, change to the current date
one_week = datetime.timedelta(weeks=1)
if current_time - last_friday_at_16 >= one_week:
    last_friday_at_16 += one_week
like image 27
moooeeeep Avatar answered Oct 16 '22 07:10

moooeeeep


This was borrowed from Jon Clements, but is the full solution:

>>> from datetime import datetime
>>> from dateutil.relativedelta import relativedelta, FR
>>> lastFriday = datetime.now() + relativedelta(weekday=FR(-1))
>>> lastFriday.replace(hour=16,minute=0,second=0,microsecond=0)
datetime.datetime(2012, 9, 28, 16, 0, 0, 0)
like image 4
bohney Avatar answered Oct 16 '22 06:10

bohney


Simplest solution without dependency:

from datetime import datetime, timedelta

def get_last_friday():
    now = datetime.now()
    closest_friday = now + timedelta(days=(4 - now.weekday()))
    return (closest_friday if closest_friday < now
            else closest_friday - timedelta(days=7))
like image 3
Bertrand Bordage Avatar answered Oct 16 '22 07:10

Bertrand Bordage