日期时间Python-下一个工作日 [英] Datetime Python - Next Business Day

查看:401
本文介绍了日期时间Python-下一个工作日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两个相关的问题:(1)我处理的所有数据都附有工作日日期。在不同的时候,我需要知道下一个工作日是什么。我已经写了类似下面的代码来确定这一点,但是我敢肯定有更好的方法。任何人? (2)理想情况下,我不仅需要知道下一个工作日,还需要知道下一个美国工作日,也就是说,不是美国市场假期的下一个工作日。

Two related issues: (1) All of the data I work with have weekday dates attached. At various points, I need to know what the next weekday is. I've written something like the code below to make this determination, but I'm sure there's a better way. Anyone? (2) Ideally, I need to know not just the next weekday, but the next US business day--that is, the next weekday that is not a US market holiday. Any help on this would also be great.

import datetime as dt

day = dt.datetime.strptime('2012-02-03','%Y-%m-%d').date()
print day#day=2012-03-02 (Friday)

if day.weekday()==4:
    day = day+dt.timedelta(days=3)
else:
    day = day+dt.timedelta(days=1)

print day#day=2012-02-06 (Monday)
day = day+dt.timedelta(days=1)
print day#day=2012-02-07 (Tuesday)


推荐答案

我会使用 dateutil.rrule

import datetime
from dateutil import rrule


holidays = [
    datetime.date(2012, 5, 1,),
    datetime.date(2012, 6, 1,),
    # ...
]

# Create a rule to recur every weekday starting today
r = rrule.rrule(rrule.DAILY,
                byweekday=[rrule.MO, rrule.TU, rrule.WE, rrule.TH, rrule.FR],
                dtstart=datetime.date.today())

# Create a rruleset
rs = rrule.rruleset()

# Attach our rrule to it
rs.rrule(r)

# Add holidays as exclusion days
for exdate in holidays:
    rs.exdate(exdate)


print rs[0]

这篇关于日期时间Python-下一个工作日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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