4

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

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')
4

1 回答 1

4

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(即 a 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)
于 2012-08-09T16:41:40.247 回答