相关疑难解决方法(0)

类型错误:“日期时间”类型的对象不是 JSON 可序列化的(具有序列化功能)

我收到此TypeError: Object of type 'datetime' is not JSON serializable错误,即使我的模型中描述了特定的序列化函数。

这是我的代码:

Flask 路线(由 React 渲染):

菜单.py

@menus_bp.route('/menus', methods=['GET', 'POST'])
def menus():

    response_object = {
        'status': 'fail',
        'message': 'Invalid payload.'
        }
    try:
        user = User.query.filter_by(id=1).first()
        if user.menu == []:
            return edit_menu()
        else:
            template = render_template('menus.html')
            response_object = {
                'status': 'success',
                'message': 'success',
                'data': [{"restaurant": user.restaurant,
                          "menu": menu,
                          "content": template}] # template passed to React
                }

            # db method
            Create_Menu(user=user)

        return jsonify(response_object), 200
    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return jsonify(response_object), 400
Run Code Online (Sandbox Code Playgroud)

方法.py …

python serialization json sqlalchemy flask

4
推荐指数
2
解决办法
5651
查看次数

如何编写和读取日期时间字典

我需要一种有效的方法来编写包含字典(包括日期时间)的文件,然后能够将它们作为字典读取。像这样的字典:

my_dict = {'1.0': [datetime.datetime(2000, 1, 1, 0, 0, 0, 000000, tzinfo=tzutc())], '2.0': [datetime.datetime(2000, 1, 1, 0, 0, 0, 000000, tzinfo=tzutc())]}
Run Code Online (Sandbox Code Playgroud)

尝试使用 json 转储:

with open("my_file.json", 'w+') as f:
    json.dump(my_dict, f)
Run Code Online (Sandbox Code Playgroud)
TypeError: Object of type 'datetime' is not JSON serializable
Run Code Online (Sandbox Code Playgroud)

还尝试将整个 dict 写为一个字符串,然后用 yaml 导入它,这几乎有效,但索引混乱。

with open("my_file", 'w+') as f:
    f.write(str(my_dict))

with open("my_file", 'r') as f:
    s = f.read()
    new_dict = yaml.load(s)

print(new_dict['1.0'][0])
Run Code Online (Sandbox Code Playgroud)
Output:   datetime.datetime(2000
Expected: 2000-01-01 00:00:00+00:00
Run Code Online (Sandbox Code Playgroud)

python datetime json dictionary eval

3
推荐指数
1
解决办法
6873
查看次数

Django:'datetime' 类型的对象不是 JSON 可序列化的

我正在尝试在我的会话中保存日期。我总是收到错误Object of type 'datetime' is not JSON serializable。我发现这这里的Django的文档:stored as seconds since epoch since datetimes are not serializable in JSON.

如何将我的保存expiry_date为秒而不是日期时间?

code = social_ticketing_form.cleaned_data['a']
expiry_date = timezone.now() + timezone.timedelta(days=settings.SOCIAL_TICKETING_ATTRIBUTION_WINDOW)
request.session[social_ticketing_cookie_name(request.event)] = {'code': code, 'expiry_date': expiry_date}
Run Code Online (Sandbox Code Playgroud)

python django

3
推荐指数
1
解决办法
7055
查看次数

AWS Lmbda TypeError:datetime.datetime(2012,8,8,21,46,24,862000)不是JSON可序列化的

我试图从m RDS数据库返回一个装备.dte字段都在DATETIME格式化,这导致我得到以下错误:

TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable
Run Code Online (Sandbox Code Playgroud)

我怎么能绕过这个?

继承我的代码:

import pymysql
import json
from rds import *

#rds settings
host  = rds_host
name = rds_name
password = rds_password
db_name = rds_db_name
port = rds_port

try:
    conn = pymysql.connect(host = host, user=name, passwd=password, db=db_name, connect_timeout=5)

except:
    raise Exception('Database Error: The server encountered an unexpected condition which prevented it from fulfilling the request.')


def handler(event, context):

    cur = conn.cursor(pymysql.cursors.DictCursor)
    #selects a user from the database …
Run Code Online (Sandbox Code Playgroud)

python amazon-web-services aws-lambda

2
推荐指数
1
解决办法
1187
查看次数

如何在Python中存储没有日期的时间,以便比较?

我有一个简单的任务,将时间存储在服务器的时区中,然后比较当前时间是否在保存的时间之前或之后。

我尝试将时间与所需时间存储为“ 2008年1月1日”。问题是,夏令时变得有些麻烦,如果我在1月1日保存“ 16:00”并尝试将其与4月1日的“ 16:00”进行比较,我会得到一个小时的差异。我希望“ 16:00”始终表示当天的“ 16:00”。

存储和比较一天中的时间并忽略日期的有效而可靠的方法是什么?我还需要它可以json序列化,因此如果需要,我可以轻松地在python和JS中操纵该值。

python datetime

2
推荐指数
2
解决办法
8643
查看次数

如何将 Python 日期时间转换为 JSON 格式?

如何将 Python DateTime 转换为 JSON 格式?

输入

from datetime import datetime
my_date = datetime.now()
Run Code Online (Sandbox Code Playgroud)

输出

{
   "start_date": '2020-05-06T09:27:51.386383'
}
Run Code Online (Sandbox Code Playgroud)

python json

2
推荐指数
1
解决办法
1万
查看次数