添加秒到python日期时间,不包括周末

时间:2012-08-09 16:09:32

标签: python datetime pandas

我正在尝试使用pandas将秒添加到python datetime,不包括周末。下面的代码有效,但我想知道是否有更简单的方法来实现这一点。

import datetime
from pandas import *
from pandas.tseries.offsets import *

def add_seconds(start_date, offset_in_seconds):
# get input date in datetime
d = datetime.strptime(start_date, '%Y-%m-%d %H:%M:%S')

# get days, hours, mins, secs
    no_of_days, remainder = divmod(offset_in_seconds, 86400)
    hours, minutes = divmod(remainder, 3600)
    minutes, seconds = divmod(minutes, 60)

# increment the input date  to the appropriate business day
    end_date_pre = d + no_of_days*BDay() 

# dial back to previous evening if hour is under 24
    if 16 + hours < 24:
    end_date = end_date_pre 
    new_end_date = datetime(end_date.year, end_date.month, end_date.day, 16, 0, 0)
    return start_date, end_date, new_end_date.strftime('%Y-%m-%d %H:%M:%S')
# dial forward to the next business day if hour exceeds 24
    elif 16 + hours >= 24:
    end_date = end_date_pre + 1*BDay()
    new_end_date = datetime(end_date.year, end_date.month, end_date.day,9, 0, 0)
    return start_date, end_date, new_end_date.strftime('%Y-%m-%d %H:%M:%S')
    else:
    return start_date, end_date, end_date.strftime('%Y-%m-%d %H:%M:%S')

1 个答案:

答案 0 :(得分:3)

dateutil包应该有用,例如

from dateutil.rrule import *    

def add_weekday_seconds(start, x):
    rr = rrule(SECONDLY, byweekday=(MO, TU, WE, TH, FR), dtstart=start, interval=x)
    return rr.after(start)

这个(1)使用rrule类来创建一个“重复日期规则”,其中包括从start开始的周一到周五的所有秒数(这是datetime),跳过每x秒;然后(2)使用after方法执行此规则,该方法返回与开始时间之后的规则匹配的第一个日期时间 - 这应该是您的答案!

在星期五晚上午夜之前的10秒开始时间内添加5秒,10秒和15秒的测试,分别导致周五午夜,周一早上午夜和周一早晨午夜后5秒的5秒:

In [131]: friday_night = datetime.datetime(2012, 8, 10, 23, 59, 50)

In [132]: add_weekday_seconds(friday_night, 5)
Out[132]: datetime.datetime(2012, 8, 10, 23, 59, 55)

In [133]: add_weekday_seconds(friday_night, 10)
Out[133]: datetime.datetime(2012, 8, 13, 0, 0)

In [134]: add_weekday_seconds(friday_night, 15)
Out[134]: datetime.datetime(2012, 8, 13, 0, 0, 5)