summaryrefslogtreecommitdiffstats
path: root/pendulum/mixins/default.py
blob: 59f985e5e160353df627cfc2fba96618a4e45acc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from __future__ import annotations

from pendulum.formatting import Formatter

_formatter = Formatter()


class FormattableMixin:
    _formatter: Formatter = _formatter

    def format(self, fmt: str, locale: str | None = None) -> str:
        """
        Formats the instance using the given format.

        :param fmt: The format to use
        :param locale: The locale to use
        """
        return self._formatter.format(self, fmt, locale)

    def for_json(self) -> str:
        """
        Methods for automatic json serialization by simplejson.
        """
        return str(self)

    def __format__(self, format_spec: str) -> str:
        if len(format_spec) > 0:
            if "%" in format_spec:
                return self.strftime(format_spec)

            return self.format(format_spec)

        return str(self)

    def __str__(self) -> str:
        return self.isoformat()