Closed pohlt closed 4 months ago
Hi,
Are you very attached to having the converter in the field? I would do this and let cattrs handle the conversion completely:
from datetime import datetime
import attrs
from cattrs.preconf.json import make_converter
@attrs.define
class K:
timestamp: datetime
conv = make_converter()
k = conv.loads("""{"timestamp": "2020-01-01T00:00:00"}""", K)
print(k)
print(conv.unstructure(k))
See, I knew there had to be a better solution! 😜 Thanks a lot, @Tinche!
No probs, let me know if you have other questions!
Description
I have to parse/structure incoming JSON strings containing timestamps which I wanted to convert to
datetime
s. I was struggling with this quite a bit, created some example code to illustrate an issue I was about to post, but finally found a working solution. But I'm still wondering if this is the correct use of the converters.Here's the code with the three options I tested (including Option C which finally worked):
Am I using the preconfigured converters correctly? Is Option C The Right Thing?