如何仅显示当前tim

2024-06-16 11:44:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在调用一个API,该API返回特定时区的当前时间(在本例中为estern)。然而,它返回了很多我不需要的数据。如何将其缩小到currentDateTime“2019-11-07T20:38-05:00”? 这是我的密码

import requests
import json
import jsonpath
import dateutil
from flask import Flask, render_template, request
from flask import jsonify, make_response

# declaring app
app = Flask(__name__, template_folder="templates")

# app route defined
@app.route('/get_time', methods=['GET'])
def get_time():
    # error handling
    try:
        time_zone = request.args.get('time_zone')
        url = "http://worldclockapi.com/api/json/" + time_zone + "/now"
        r = requests.get(url)
    except Exception:
        return make_response(jsonify({"Error": "Some error message"}), 400)
    return r.json()
    # I could not figure out how to display only Current Date Time for this error handling scenario
    # If I do narrow it down the invalid time zone error is not displayed.

    # this will return error if condition not met
    if response.status_code != 200:
        print("Error on response")
        return response.status_code, response.text

# main app
if __name__ == '__main__':
    app.run(debug=True)

以下是我得到的回报:

{
  "$id": "1", 
  "currentDateTime": "2019-11-07T20:38-05:00", 
  "currentFileTime": 132176327192699737, 
  "dayOfTheWeek": "Thursday", 
  "isDayLightSavingsTime": false, 
  "ordinalDate": "2019-311", 
  "serviceResponse": null, 
  "timeZoneName": "Eastern Standard Time", 
  "utcOffset": "-05:00:00"
}

Tags: fromimportapijsonappzonegetreturn
2条回答

试试像这样的东西

return r.json()["currentDateTime"]

修改reutrn,让我知道它是否工作

return r.json()["currentDateTime"]

希望这有帮助

相关问题 更多 >