我正在尝试将秒数添加到 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')