循环浏览除周末外的日期 [英] Loop through dates except for weekends

查看:61
本文介绍了循环浏览除周末外的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个脚本,其中包含用于不同功能的日期参数,并且我希望它在01-01-201206-09-2012之间循环(不包括周末).我试图找出一种可以使用时间增量的方法,因为我的脚本输出的文件带有文件名中使用的日期,例如:

So I have a script that has date arguments for different functions and I want it to loop through 01-01-2012 to 06-09-2012 not including weekends. Im trying to figure out a way I can use time delta because my script outputs files with the date used in the name of the file for example:

items = (functions.getItems(item,date)
    print items
    test = sum(abs(l[-1]) for l in items)
    total = open('total' +str(datetime.today- datetime.timedelta(1)),'a')

我希望timedelta(1)循环显示每个日期,以便输出文件在第一天的格式为total2012-01-01并循环显示,直到创建文件total2012-06-09.此外,项目的日期参数的格式为MM-DD-YYYY

I want timedelta(1) to cycle through each date so that the output file would have the format of total2012-01-01 for the first day and cycle through until it created the file total2012-06-09. Also the date argument for items has the format of MM-DD-YYYY

我认为我可以这样做:

sd = 01-01-2012
ed = 06-09-2012
delta = datetime.timedelta(days=1)
diff = 0
while sd != ed
    # do functions 
    # (have output files (datetime.today - datetime.delta(diff))
    diff +=1
    sd+=delta

所以本质上我只是想弄清楚如何让函数以01-01-2012开头并以06-10-2012结尾(不包括周末)循环.我在弄清楚如何排除周末以及如何使其按正确顺序循环方面遇到困难

So essentially I'm just trying to figure out how can I loop through having the function start with 01-01-2012 and ending with 06-10-2012 excluding weekends. I'm having trouble figuring out how to exclude weekends and how to get it to loop in the proper order

谢谢

推荐答案

使用

Use the datetime.weekday() method. It returns values between zero and six, related to the weekdays. Saturday value is 5 and Sunday value is 6; so, if you skip the operation when these values appear, you skip weekdends:

start = datetime(2012, 1, 1)
end = datetime(2012, 10, 6)
delta = timedelta(days=1)
d = start
diff = 0
weekend = set([5, 6])
while d <= end:
    if d.weekday() not in weekend:
        diff += 1
    d += delta

这篇关于循环浏览除周末外的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆