循环通过除周末以外的日期

时间:2012-06-11 17:25:39

标签: python datetime loops

所以我有一个脚本,其中包含不同函数的日期参数,我希望它循环遍历01-01-201206-09-2012,不包括周末。我试图找出一种方法,我可以使用时间增量,因为我的脚本输出的文件具有文件名中使用的日期,例如:

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

我以为我可以这样做:

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结束,不包括周末。我无法弄清楚如何排除周末以及如何让它以正确的顺序循环

谢谢

3 个答案:

答案 0 :(得分:15)

使用datetime.weekday()方法。它返回0到6之间的值,与工作日相关。星期六值为5,星期日值为6;因此,如果在出现这些值时跳过操作,则跳过周末:

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

答案 1 :(得分:1)

@ brandizzi的答案在语法上更具美感,但作为替代方案,您可以使用以下

$Groups = (Get-AdGroup -filter * | Where     {
            ($_.name -like "*") 

} | select ObjectGUID -expandproperty ObjectGUID)


$Table = @()

$Record = [ordered]@{
    "Group _ObjectGUID" = ""
    "Name" = ""
    "SamAccountName" = ""
    "Member_ObjectGUID" = ""
}


Foreach ($Group in $Groups)
{
    $Arrayofmembers = Get-ADGroupMember -Recursive -identity $Group  | select name,samaccountname,ObjectGUID

    foreach ($Member in $Arrayofmembers)
    {
        $Record."Group _ObjectGUID" = $Group
        $Record."Name" = $Member.name
        $Record."SamAccountName" = $Member.SamAccountName
        $Record."Member_ObjectGUID" = $Member.ObjectGUID
        $objRecord = New-Object PSObject -property $Record
        $Table += $objrecord
    }

}

$Table | export-csv "C:\temp\AD_group_members.txt" -NoTypeInformation

答案 2 :(得分:1)

对于<html> <head> <link href="https://fonts.googleapis.com/css?family=Cabin+Sketch" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> </head> <body> <div id="App"> <!-- this is where the root react component will get rendered --> </div> </body> </html> ,可以使用freq = 'B'来实现。

business day frequency

为您提供:

import pandas as pd
dt = pd.date_range(start=datetime.date.today(), periods=10, freq='B')
dt

您还通过以下方式检查日期名称:

DatetimeIndex(['2018-08-13', '2018-08-14', '2018-08-15', '2018-08-16',
               '2018-08-17', '2018-08-20', '2018-08-21', '2018-08-22',
               '2018-08-23', '2018-08-24'],
              dtype='datetime64[ns]', freq='B')