xingfanxia commited on
Commit
a2436f4
·
unverified ·
1 Parent(s): 48c6f75

fix: fix usage stats error when it's the first day of the month (#498)

Browse files
Files changed (1) hide show
  1. modules/openai_func.py +9 -2
modules/openai_func.py CHANGED
@@ -49,8 +49,9 @@ def get_usage(openai_api_key):
49
  total_used=0
50
  return f"**API使用情况解析失败**"
51
  if balance == 0:
52
- last_day_of_month = datetime.datetime.now().strftime("%Y-%m-%d")
53
- first_day_of_month = datetime.datetime.now().replace(day=1).strftime("%Y-%m-%d")
 
54
  usage_url = f"{shared.state.usage_api_url}?start_date={first_day_of_month}&end_date={last_day_of_month}"
55
  try:
56
  usage_data = get_billing_data(openai_api_key, usage_url)
@@ -80,3 +81,9 @@ def get_usage(openai_api_key):
80
  except Exception as e:
81
  logging.error(f"获取API使用情况失败:"+str(e))
82
  return standard_error_msg + error_retrieve_prompt
 
 
 
 
 
 
 
49
  total_used=0
50
  return f"**API使用情况解析失败**"
51
  if balance == 0:
52
+ curr_time = datetime.datetime.now()
53
+ last_day_of_month = get_last_day_of_month(curr_time).strftime("%Y-%m-%d")
54
+ first_day_of_month = curr_time.replace(day=1).strftime("%Y-%m-%d")
55
  usage_url = f"{shared.state.usage_api_url}?start_date={first_day_of_month}&end_date={last_day_of_month}"
56
  try:
57
  usage_data = get_billing_data(openai_api_key, usage_url)
 
81
  except Exception as e:
82
  logging.error(f"获取API使用情况失败:"+str(e))
83
  return standard_error_msg + error_retrieve_prompt
84
+
85
+ def get_last_day_of_month(any_day):
86
+ # The day 28 exists in every month. 4 days later, it's always next month
87
+ next_month = any_day.replace(day=28) + datetime.timedelta(days=4)
88
+ # subtracting the number of the current day brings us back one month
89
+ return next_month - datetime.timedelta(days=next_month.day)