marshmallow-code / marshmallow-code/marshmallow

Format datetime field with millisecond precision

Open
#2,032 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
Python
Stars
7.2k
Forks
738
Avg merge
1d 23h
Merged PRs (30d)
7

Description

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

Contributor guide

Open the contributing guide

Research direction

The issue names no repository files or tests; begin with fields.Function and Schema and reproduce the shown Blah().dumps example. Define done as a supported way to serialize datetime values with millisecond precision without coupling the mapping to dict versus object input, with tests covering both inputs.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.