dfurtado / dataclass-csv

Map CSV to Data Classes
Other
195 stars 21 forks source link

Dateformat decorator does not apply to DataclassWriter #51

Open rosterloh opened 2 years ago

rosterloh commented 2 years ago

When reading datetime fields from a file the @dateformat() works well but when writing the same dataclass with DataclassWriter it does not write them to the file in this format.

dfurtado commented 2 years ago

Thanks for submitting this issue. 👍

I will investigate a good way of doing it and add a fix for it.

/Daniel

bleach31 commented 2 years ago

Thank you for a very good library. I look forward to this update.

If there is a workaround that can be done with the v1.4.0, could you please let me know?

dfurtado commented 2 years ago

Hi @bleach31 , thanks for your kind words. I'm working on a solution for this and it should come out in the next release pretty soon. 🙂

bleach31 commented 2 years ago

Thank you for your comment. I am looking forward to next release!

Anyway, here is workaround that I'm using so far. I hope this will help someone until next release.

# Create mydatetime to override the behaviour of the initializing (new) and saving (str) functions of  datetime.

class mydatetime(datetime.datetime):
    def __new__(cls, *args, **kwargs):
        if len(args) == 1 and type(args[0]) is str:
            # Must not conflict with superclass implementations.
            # https://github.com/python/cpython/blob/d174ebe91ebc9f7388a22cc81cdc5f7be8bb8c9b/Lib/datetime.py#L1563
            return super().strptime(args[0], "%Y-%m-%d %H:%M:%S.%f")
        else:
            return super().__new__(cls, *args, *kwargs)

    def __str__(self):
        result = super().__str__()
        if int(self.microsecond) == 0:
            # In the default str function, when microsecond is 0, the . %f" is not output, so make it output.
            return result + ".0"
        else:
            return result