Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Format datetime field with millisecond precision #2032

Open
1Mark opened this issue Aug 9, 2022 · 1 comment
Open

Format datetime field with millisecond precision #2032

1Mark opened this issue Aug 9, 2022 · 1 comment

Comments

@1Mark
Copy link

1Mark commented Aug 9, 2022

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
Copy link
Author

1Mark commented Aug 9, 2022

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant