下記のエラーがでます、datetimeをどうJSONでおくればよいのでしょうか?
error
1raise TypeError("Object of type '%s' is not JSON serializable" % 2> o.__class__.__name__) 3E TypeError: Object of type 'datetime' is not JSON serializable
flask
1 2def test_events(app): 3 path = '/v1/events' 4 payload = { 5 "all_id": "all_id", 6 "events": [ 7 { 8 "type": "followed", 9 "re_id":8990, 10 "module_": "id001", 11 "time_":datetime(2018, 8, 24, 20, 7, 17) 12 }, 13 14 ] 15} 16 17 _header = "001_1:001" 18 headers = {'Authorization': 'Basic %s' % _header} 19 20 with app_made_events.test_request_context(path, 21 method="POST", 22 headers=headers, 23 content_type='application/json', 24 data=json.dumps(payload)) as req: 25 26 func = _events(req.request, _id="_id001") 27 res = jsonify({'message': 'error', 'result': 201}), 201 28 assert res[0].json == func[0].json 29 assert res[1] == func[1]
*追記
上記コードは、自分で試してたどり着いたコードであり、本来の問題は、isoformatでjsonを送れないという問題でつまづいていました。 "time_":"2014-09-24T19:14:53.000Z",のようにJSONに記述してpostリクエストを送る場合です。
ただ、それを実行するとsqlalchemy.exc.StatementError: (builtins.TypeError) SQLite DateTime type only accepts Python datetime and date objects as input. というエラーで怒られてしまいます。
python側の受け取り方はこのようなコードです。
def parse_datetime(datetime_string): if datetime_string is not None: dt = parse(datetime_string) if dt.tzinfo is not None and dt.tzinfo.utcoffset(dt) is not None: print(datetime_string+" is aware.") return dt.astimezone(timezone('UTC')).strftime("%Y-%m-%d %H:%M:%S") else: print(datetime_string+" is native.") return dt.strftime("%Y-%m-%d %H:%M:%S") return None
start_time = parse_datetime(events.get("_time"))
datetimeをserializeできれば、この問題を解決できるかと思いご回答頂きましたが、下記でご教示頂いたやり方を実行してみましたが、上記のようなエラーがででpythonで受け取れないようです。
何かtips頂けませんでしょうか?
*補足
datetime_string
日付のstringオブジェクト"2014-09-24T19:14:53.000Z"が入る。
UTCのタイムゾーンの持つawareな日付
dt = parse(datetime_string)
datetime.datetime(2014, 9, 24, 19, 14, 53, tzinfo=tzutc())
stringオブジェクトをUTCのタイムゾーンを持つdatetimeオブジェクトにパースする
「UTC(協定世界時)」とは、世界各地の標準時を決めるときの基準となる「世界標準時」のことです。たとえば日本の標準時(JST)は「UTC」よりも 9時間進んでいるため「UTC+09:00」と表示されます。
if dt.tzinfo is not None and dt.tzinfo.utcoffset(dt) is not None:
datetimeがタイムゾーンをもっているかどうか、つまりawareな日付かnativeな日付かどかをチェックする
dt.tzinfo 出力結果: tzutc() dt.tzinfo.utcoffset(dt) 出力結果: datetime.timedelta(0)
dt.tzinfo.utcoffset(dt)は、UTCとの差とローカルな時間(例えば、JTC、日本時間)との差がどれだけあるかどうかを出力。今回は、UTCのタイムゾーンを持つ日付との差分をだしているため、0と出力されている。
(Pdb) p dt.astimezone() datetime.datetime(2014, 9, 25, 4, 14, 53, tzinfo=datetime.timezone(datetime.timedelta(0, 32400), 'JST')) (Pdb) p timezone('UTC') <UTC> (Pdb) p dt.astimezone(timezone('UTC')) datetime.datetime(2014, 9, 24, 19, 14, 53, tzinfo=<UTC>)
dt.astimezone()は、ローカルの時間に変換するのため、JSTの時間で8時間ぐらいの差が出力結果にある。
今回は、UTCで最終的には出力したいため、timezoneでUTCになおして出力する。
return dt.astimezone(timezone('UTC')).strftime("%Y-%m-%d %H:%M:%S") datetime.datetime(2014, 9, 24, 19, 14, 53, tzinfo=<UTC>)は、 データベースに入った後は、マイクロ秒まではいってします。 2014-09-24 19:14:53.000000|
ここで、問題、.strftime("%Y-%m-%d %H:%M:%S")はマイクロ秒を落とすためにstringオブジェクトになおして整形している。しかし、データベースのモデル定義は、datatimeであるため、insertすることができない。
以下、2つの方法を探る必要がある。
方法1:データベースのモデルをマイクロ秒までいれないように何か定義をし直すことができるかを探る。
方法2: datetimeのまま、整形できるような関数や方法を探る。
*日付に関わる役立つURL
https://torina.top/detail/338/
https://uxmilk.jp/12626
https://qiita.com/takaki@github/items/b1a380a0a644170f5885
https://docs.python.org/ja/3/library/datetime.html
https://qiita.com/takaki@github/items/b1a380a0a644170f5885
回答3件
あなたの回答
tips
プレビュー