bobglu
bobglu

Reputation: 95

JSON String Timestamp Deserialized into Marshmallow Datetime Not Working

So I have a dataclass and I'm automatically constructing the Marshmallow class schema from it using class_schema. I have to make the schema this way, but I'm running into issues where it won't let me pass in a JSON with a string, because it's expecting a "datetime". I feel like there's something obvious I'm missing

from dataclasses import dataclass, field
from typing import List, Optional
import datetime as dt
from marshmallow_dataclass import class_schema
import marshmallow.fields as ma_fields

@dataclass
class ExampleClass:
    timestamp_field: dt.datetime = field(
        default=dt.datetime(2024, 10, 16),
        metadata={"marshmallow_field": ma_fields.DateTime(format='%Y-%m-%dT%H:%M:%S')}
    )

# Generate schema
ExampleSchema = class_schema(ExampleClass)
schema_instance = ExampleSchema()
input_data = {
    "timestamp_field": "2024-03-12T56:00:00",
}
data = schema_instance.dump(input_data)

This throws an error AttributeError: 'str' object has no attribute 'strftime'. If I change the last line to schema_instance.load(input_data), I get this error: TypeError: _base_schema.<locals>.BaseSchema.make_data_class() got an unexpected keyword argument 'many'. I just want it to be turned into an ExampleClass(timestamp_field=dt.datetime(...) object so I can use that downstream.

Isn't the point of the Marshmallow Schema class so it can automatically deserialize from the string to the actual datetime? What am I doing wrong here?

Upvotes: 1

Views: 27

Answers (0)

Related Questions