如何将日期范围传递给脚本

  • 本文关键字:脚本 范围 日期 python
  • 更新时间 :
  • 英文 :


我有以下代码:

def parse_args():
"""Takes in arguments from command when run
:return: date
"""
parser = argparse.ArgumentParser(sys.argv)
parser.add_argument('-d')
args = parser.parse_args()
d_param = args.d
if d_param is None:
d_param = datetime.today().date() - BDay(1)
else:
d_param = datetime.strptime(d_param, "%Y%m%d")
d_param = d_param.date()
return d_param

所以目前它只接受一个日期参数。例如:script.py -d 20210110如何通过日期范围?就像我想让剧本从1月1日到1月10日运行一样。所以基本上是20210101到20210110。是否可以提供一个日期范围或一个日期的选项?

附言-目前我正在使用脚本中的日期来计算一些字段。

您可以有一个开始日期一个可选的结束日期:

def parse_args():
"""Takes in arguments from command when run
:return: date
"""
parser = argparse.ArgumentParser(sys.argv)
parser.add_argument('-s')
parser.add_argument('-e')
args = parser.parse_args()
start_param = args.s
end_param = args.e
if start_param is None:
start_param = datetime.today().date() - BDay(1)
else:
start_param = datetime.strptime(d_param, "%Y%m%d")

if end_param is None:
end_param = # PUT YOUR DEFAULT END DATE HERE
else:
end_param = datetime.strptime(d_param, "%Y%m%d")
start_param = d_param.date()
end_param = d_param.date()
return start_param, end_param

这就是我最终所做的:

if d_param is None:
start_date = end_date = (datetime.today().date() - BDay(1)).date()
else:
dates = d_param.split('-')
# User supplied "-d 20170101" argument.
if len(dates) == 1:
start_date = end_date = datetime.strptime(dates[0], "%Y%m%d").date()
# User supplied "-d 20170101-20170131" argument.
else:
start_date = datetime.strptime(dates[0], "%Y%m%d").date()
end_date = datetime.strptime(dates[1], "%Y%m%d").date()
# Weekdays between start_date and end_date. Does not take holidays
# into consideration.
date_range = pd.bdate_range(start_date, end_date)
# If length is 0, it means there are no weekdays between start_date
# and end_date.
if len(date_range) == 0:
log.error('No weekdays between start date {} and end date {}'
.format(start_date, end_date))
sys.exit(1)

相关内容

  • 没有找到相关文章

最新更新