I am trying to add seconds to python datetime excluding weekends using pandas. The code below works, but I would like to know if there is a simpler way to achieve this.
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')
The dateutil package should be helpful, e.g.
This (1) uses the
rruleclass to creates a “repeating date rule” that includes all seconds within Monday through Friday starting onstart(which is adatetime), skipping everyxseconds; and then (2) executes this rule using theaftermethod which returns the first datetime matching the the rule after the start time — which should be your answer!Tests of adding 5, 10, and 15 seconds to a start time of 10 seconds before midnight on Friday night, resulting in, respectively, 5 seconds before midnight on Friday, midnight Monday morning, and 5 seconds after midnight Monday morning: