简体   繁体   English

如何使用Python或SQL计算X周的过去几天?

[英]How to compute X week days into the past, using Python or SQL?

I need to compute exactly 5 week days into the past. 我需要准确计算过去5周的时间。 eg if today's date is 2015-05-07 I need my program to give me 2015-04-30. 例如,如果今天的日期是2015-05-07我需要我的计划给我2015-04-30。

So far I tried is this 到目前为止,我试过这个

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

This gives 5 days exactly into the past. 这给了过去5天。 But I need 5th weekday into the past. 但是我需要在工作日的第五天过去。 The purpose I need this is because I have a database table which consists of some data and I need to write a Python script which fetches the data for last 5 days. 我需要这个的目的是因为我有一个数据库表,其中包含一些数据,我需要编写一个Python脚本来获取最近5天的数据。

Five days in the past is simply: 过去五天简单地说:

select date_sub(CURDATE(), interval 5 day)

If by week day you mean Mon - Fri, then the logic is actually rather simple. 如果按星期一天你的意思是周一至周五,那么逻辑实际上相当简单。 5 week days are one week, which is 7 days (at least in the United States). 5 工作日是一周,这是7天(至少在美国)。 So the answer to your question is 所以你的问题的答案是

select date_sub(CURDATE(), interval 7 day)

Note that other numbers of days would require more complex logic, using CASE . 请注意,使用CASE ,其他天数需要更复杂的逻辑。

Python datetime objects have a isoweekday() method to help with this. Python datetime对象有一个isoweekday()方法来帮助解决这个问题。 This method returns a numeric value corresponding to the day of the week. 此方法返回与星期几对应的数值。 So for example, Monday is the integer 1. You want to skip Saturday and Sunday, these correspond to 6 and 7 respectfully. 因此,例如,星期一是整数1.您想要跳过星期六和星期日,这些分别对应于6和7。 We can use this to backtrack: 我们可以用它来回溯:

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 have used your date format. 我使用了你的日期格式。 But you can easily change this. 但你可以轻松改变这一点。

Instead of isoweekday() you can use weekday() but now Monday will be returned as 0 and Sunday will be returned as 6. 您可以使用weekday()而不是isoweekday() ,但现在星期一将返回0,星期日将返回6。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM