You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中将Postman传入的JSON日期参数转为datetime可用的整数?

问题解决方法

错误原因

你从POST请求的JSON payload中获取的fromDate和toDate是逗号分隔的字符串类型,而datetime()构造函数需要传入年、月、日三个独立的整数参数,直接传入字符串会触发类型错误。

修复步骤

  1. 先将拿到的日期字符串按逗号拆分,逐个转换为整数
  2. 补充GET请求的默认值逻辑,避免空值传入报错
  3. 新增参数格式校验,避免非法格式请求触发服务异常

修改后代码

from datetime import datetime
from flask import request
import MetaTrader5 as mt

@app.route("/", methods=['POST', 'GET'])
def historyOrderTotal():
    # 设置默认日期范围:2020年1月1日至今
    from_date = datetime(2020, 1, 1)
    to_date = datetime.now()
    
    if request.method == 'POST':
        try:
            # 拆分日期字符串并转换为整数
            from_year, from_month, from_day = map(int, request.json['fromDate'].split(','))
            to_year, to_month, to_day = map(int, request.json['toDate'].split(','))
            # 构造datetime对象
            from_date = datetime(from_year, from_month, from_day)
            to_date = datetime(to_year, to_month, to_day)
        except (ValueError, KeyError) as e:
            # 参数格式错误时返回提示
            return {"code": 400, "msg": "日期参数格式错误,请遵循'年, 月, 日'格式"}, 400

    # 初始化MT5,增加失败判断
    if not mt.initialize():
        return {"code": 500, "msg": "MetaTrader5初始化失败"}, 500

    history_orders = mt.history_orders_total(from_date, to_date)
    return {"code": 200, "data": history_orders}

更稳妥的参数传递方案(可选)

你可以调整POST payload的格式,直接传递ISO标准日期字符串,解析逻辑更通用、容错性更高:

调整后的payload

{
     "fromDate" : "2020-01-01",
     "toDate": "2020-11-08"
}

对应解析代码

from_date = datetime.strptime(request.json['fromDate'], "%Y-%m-%d")
to_date = datetime.strptime(request.json['toDate'], "%Y-%m-%d")

内容的提问来源于stack exchange,提问作者Yomal Senarath

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 12:27:05