31

trying to get the syntax of the Python 3.7 new dataclass right.

if I want to include a datetime value in my dataclass,

import datetime
from dataclasses import dataclass

@dataclass
class MyExampleWithDateTime:
    mystring: str
    myint: int
    mydatetime: ???

What should I write for ??? for a datetime field?

576i
  • 7,579
  • 12
  • 55
  • 92

1 Answers1

52

Like this:

@dataclass
class MyExampleWithDateTime:
    mystring: str
    myint: int
    mydatetime: datetime.datetime
wim
  • 338,267
  • 99
  • 616
  • 750
  • Are there any useful tips for making this json serializable outside of creating a customer encoder? Referring to the error message: `TypeError: Object of type datetime is not JSON serializable` that results from: `ex = MyExampleWithDateTime('a', 1, datetime.datetime.now())`. and then: `json.dumps(asdict(ex))` results in: ` – user9074332 Jan 03 '21 at 05:01
  • JSON does not have datetime.datetime objects. You could store the components of `mydatetime` as numbers (e.g. `mydt_yr`, `mydt_mo`, `mydt_d`, etc.), then define a @property `mydatetime` to combine the units, with a setter to split out the units. – eksortso Jun 15 '21 at 00:35
  • 1
    Or, you could represent the `datetime.datetime` object as an ISO 8601-formatted string, then do something similar with a property and a setter. – eksortso Jun 15 '21 at 00:41
  • @eksortso checkout orjson – Jordan Morris Dec 05 '21 at 11:11