ComplexDateTimeField 转换中的“'str' 对象没有属性 'strftime'”

"'str' object has no attribute 'strftime'" in ComplexDateTimeField conversion

好吧,我正在实施一个测试用例,但我遇到了一些问题。

这是代码示例

datetime_one = mongo.ComplexDateTimeField()._convert_from_string('2019, 12, 20, 19, 24, 10, 451923')

visitor = Visit()
visitor.user_id = '750645c7-bf66-4023-9a2d-9c942a25f6cd'
visitor.timestamp = mongo.ComplexDateTimeField().to_mongo(datetime_one)
visitor.save()

访问者是来自class访问的对象:

from datetime import datetime
import mongoengine as mongo

class Visit(mongo.Document):

    user_id = mongo.UUIDField(required=True)
    timestamp = mongo.ComplexDateTimeField(required=True, default=datetime.utcnow, editable=False)

当我尝试 运行 这段代码时,我在 visitor.timestamp...

行中遇到错误

AttributeError: 'str' object has no attribute 'strftime'

我做错了什么?

您需要使用 datetime 个实例,而不是字符串,您不需要使用 to_mongo_convert_from_string.

ComplexDateTimeField 的文档中所述,与常规 DateTimeField 的唯一区别是日期将在后台存储为字符串,但您与该属性的任何交互都将与datetime.

见下文:

class Visit(Document):
    timestamp = ComplexDateTimeField()

visit = Visit(timestamp=datetime.utcnow())
visit.save()
assert isinstance(visit.timestamp, datetime)

# print object as it is stored in mongodb
print(Visit.objects.as_pymongo())
# Output: [{'timestamp': '2020,01,23,22,24,21,449017', '_id': ObjectId('5e2a1d15f3ede875e9c0b806')}]

如果您需要更多代码示例,请随时查看相应的 test file