marshmallow icon indicating copy to clipboard operation
marshmallow copied to clipboard

Format datetime field with millisecond precision

Open 1Mark opened this issue 3 years ago • 1 comments

Since datetime.datetime.strftime doesn't have an easy way to convert a datetime with microsecond precision to millisecond precision this also leaks into Marshmallow. I have come up with

from marshmallow import fields
from datetime import datetime

from marshmallow import Schema
class Blah(Schema):
    date_time = fields.Function(
        lambda dictionary: dictionary["date_time"].strftime("%FT%T.%f")[:-3] + "Z"
    )
x = datetime.utcnow()
print(f"{x=}") # prints x=datetime.datetime(2022, 8, 9, 16, 38, 44, 165105)
Blah().dumps({"date_time":x}) # prints '{"date_time": "2022-08-09T16:38:44.165Z"}'

Is there a cleaner way to do this?

I also dislike the fact that this is now linked to the input type, if I now use a class to dump the data from instead of a dict I will have to change the mapping to be

class Blah(Schema):
    date_time = fields.Function(
        lambda some_instance: some_instance.date_time.strftime("%FT%T.%f")[:-3] + "Z"
    )

I feel I'm missing something

1Mark avatar Aug 09 '22 16:08 1Mark

This is another possibility, which is better since we don't need to worry about the input type

class Blah(Schema):
    date_time = fields.DateTime()

    @post_dump
    def post_dump_processing(self, data, **kwargs):
        data["date_time"] = data["date_time"][:-3]+"Z"
        return data

#513 sounds promising too.

1Mark avatar Aug 09 '22 20:08 1Mark