How do I calculate X weekly days in the past using Python or SQL?

I need to calculate exactly 5 days in the past. for example if today is the date 2015-05-07 I need my program to give me 2015-04-30.

So far I have tried this

today = datetime.date.today() - datetime.timedelta(5)

      

This gives 5 days in the past. But I need a 5th weekday in the past. The goal I need is that I have a database table that consists of some data and I need to write a Python script that retrieves the data for the last 5 days.

+3


source to share


2 answers


Python objects datetime

have a method isoweekday()

to help with this. This method returns a numeric value corresponding to the day of the week. So, for example, Monday is an integer 1. You want to skip Saturday and Sunday, they match 6 and 7 respectfully. We can use this to return:

from datetime import datetime, timedelta                                              

def workingday(d, no_of_days):                                                              
    backdate = d                                                                      
    count = 0                                                                         
    while count < no_of_days:                                                                  
        backdate = backdate - timedelta(1)                                              
        if backdate.isoweekday() in (6,7):                                            
            continue                                                                  
        count += 1                                                                    
    return backdate.strftime("%Y-%m-%d")


d = datetime.strptime("2015-05-07","%Y-%m-%d")                                        
print workingday(d, 5)

Output:

2015-04-30 

      



I used the date format. But you can easily change that.

isoweekday()

You can use instead weekday()

, but now Monday will be returned as 0 and Sunday will be returned as 6.

+1


source


Five days in the past is simple:

select date_sub(CURDATE(), interval 5 day)

      

If on weekdays you mean Mon-Fri, then the logic is actually pretty simple. 5 weekly days is one week which is 7 days (at least in the United States). So the answer to your question is:



select date_sub(CURDATE(), interval 7 day)

      

Note that other numbers of days require more complex logic using CASE

.

+2


source







All Articles