Exemple #1
0
    def format(self, dt, fmt, locale=None):
        """
        Formats a DateTime instance with a given format and locale.

        :param dt: The instance to format
        :type dt: pendulum.DateTime

        :param fmt: The format to use
        :type fmt: str

        :param locale: The locale to use
        :type locale: str or Locale or None

        :rtype: str
        """
        if not locale:
            locale = pendulum.get_locale()

        locale = Locale.load(locale)

        result = self._FORMAT_RE.sub(
            lambda m: m.group(1)
            if m.group(1)
            else m.group(2)
            if m.group(2)
            else self._format_token(dt, m.group(3), locale),
            fmt,
        )

        return decode(result)
Exemple #2
0
    def format(self, dt, fmt, locale=None):
        """
        Formats a DateTime instance with a given format and locale.

        :param dt: The instance to format
        :type dt: pendulum.DateTime

        :param fmt: The format to use
        :type fmt: str

        :param locale: The locale to use
        :type locale: str or Locale or None

        :rtype: str
        """
        if not locale:
            locale = pendulum.get_locale()

        locale = Locale.load(locale)

        result = self._FORMAT_RE.sub(
            lambda m: m.group(1) if m.group(1) else m.group(2)
            if m.group(2) else self._format_token(dt, m.group(3), locale),
            fmt,
        )

        return decode(result)
Exemple #3
0
def test_locale():
    dt = pendulum.datetime(2000, 11, 10, 12, 34, 56, 123456)
    pendulum.set_locale("fr")

    assert pendulum.get_locale() == "fr"

    assert dt.format("MMMM") == "novembre"
    assert dt.date().format("MMMM") == "novembre"
Exemple #4
0
def test_locale():
    dt = pendulum.datetime(2000, 11, 10, 12, 34, 56, 123456)
    pendulum.set_locale('fr')

    assert pendulum.get_locale() == 'fr'

    assert dt.format('MMMM') == 'novembre'
    assert dt.date().format('MMMM') == 'novembre'
Exemple #5
0
    def parse(
            self,
            time,  # type: str
            fmt,  # type: str
            now,  # type: pendulum.DateTime
            locale=None,  # type:  typing.Union[str, None]
    ):  # type: (...) -> dict
        """
        Parses a time string matching a given format as a tuple.

        :param time: The timestring
        :param fmt: The format
        :param now: The datetime to use as "now"
        :param locale: The locale to use

        :return: The parsed elements
        """
        escaped_fmt = re.escape(fmt)

        tokens = self._FROM_FORMAT_RE.findall(escaped_fmt)
        if not tokens:
            return time

        if not locale:
            locale = pendulum.get_locale()

        locale = Locale.load(locale)

        parsed = {
            "year": None,
            "month": None,
            "day": None,
            "hour": None,
            "minute": None,
            "second": None,
            "microsecond": None,
            "tz": None,
            "quarter": None,
            "day_of_week": None,
            "day_of_year": None,
            "meridiem": None,
            "timestamp": None,
        }

        pattern = self._FROM_FORMAT_RE.sub(
            lambda m: self._replace_tokens(m.group(0), locale), escaped_fmt)

        if not re.match(pattern, time):
            raise ValueError("String does not match format {}".format(fmt))

        re.sub(pattern,
               lambda m: self._get_parsed_values(m, parsed, locale, now), time)

        return self._check_parsed(parsed, now)
Exemple #6
0
    def parse(
        self,
        time,  # type: str
        fmt,  # type: str
        now,  # type: pendulum.DateTime
        locale=None,  # type:  typing.Union[str, None]
    ):  # type: (...) -> dict
        """
        Parses a time string matching a given format as a tuple.

        :param time: The timestring
        :param fmt: The format
        :param now: The datetime to use as "now"
        :param locale: The locale to use

        :return: The parsed elements
        """
        escaped_fmt = re.escape(fmt)

        tokens = self._FORMAT_RE.findall(escaped_fmt)
        if not tokens:
            return time

        if not locale:
            locale = pendulum.get_locale()

        locale = Locale.load(locale)

        parsed = {
            "year": None,
            "month": None,
            "day": None,
            "hour": None,
            "minute": None,
            "second": None,
            "microsecond": None,
            "tz": None,
            "quarter": None,
            "day_of_week": None,
            "day_of_year": None,
            "meridiem": None,
            "timestamp": None,
        }

        pattern = self._FORMAT_RE.sub(
            lambda m: self._replace_tokens(m.group(0), locale), escaped_fmt
        )

        if not re.match(pattern, time):
            raise ValueError("String does not match format {}".format(fmt))

        re.sub(pattern, lambda m: self._get_parsed_values(m, parsed, locale, now), time)

        return self._check_parsed(parsed, now)
Exemple #7
0
    def in_words(self, locale=None, separator=' '):
        """
        Get the current interval in words in the current locale.

        Ex: 6 jours 23 heures 58 minutes

        :param locale: The locale to use. Defaults to current locale.
        :type locale: str

        :param separator: The separator to use between each unit
        :type separator: str

        :rtype: str
        """
        periods = [
            ('year', self.years),
            ('month', self.months),
            ('week', self.weeks),
            ('day', self.remaining_days),
            ('hour', self.hours),
            ('minute', self.minutes),
            ('second', self.remaining_seconds)
        ]

        if locale is None:
            locale = pendulum.get_locale()

        locale = pendulum.locale(locale)
        parts = []
        for period in periods:
            unit, count = period
            if abs(count) > 0:
                translation = locale.translation(
                    'units.{}.{}'.format(
                        unit, locale.plural(abs(count))
                    )
                )
                parts.append(translation.format(count))

        if not parts and abs(self.microseconds) > 0:
            translation = locale.translation(
                'units.second.{}'.format(locale.plural(1))
            )
            us = abs(self.microseconds) / 1e6
            parts.append(
                translation.format('{:.2f}'.format(us))
            )

        return decode(separator.join(parts))
Exemple #8
0
    def in_words(self, locale=None, separator=" "):
        """
        Get the current interval in words in the current locale.

        Ex: 6 jours 23 heures 58 minutes

        :param locale: The locale to use. Defaults to current locale.
        :type locale: str

        :param separator: The separator to use between each unit
        :type separator: str

        :rtype: str
        """
        periods = [
            ("year", self.years),
            ("month", self.months),
            ("week", self.weeks),
            ("day", self.remaining_days),
            ("hour", self.hours),
            ("minute", self.minutes),
            ("second", self.remaining_seconds),
        ]

        if locale is None:
            locale = pendulum.get_locale()

        locale = pendulum.locale(locale)
        parts = []
        for period in periods:
            unit, count = period
            if abs(count) > 0:
                translation = locale.translation(
                    "units.{}.{}".format(unit, locale.plural(abs(count)))
                )
                parts.append(translation.format(count))

        if not parts:
            if abs(self.microseconds) > 0:
                unit = "units.second.{}".format(locale.plural(1))
                count = "{:.2f}".format(abs(self.microseconds) / 1e6)
            else:
                unit = "units.microsecond.{}".format(locale.plural(0))
                count = 0
            translation = locale.translation(unit)
            parts.append(translation.format(count))

        return decode(separator.join(parts))
Exemple #9
0
    def in_words(self, locale=None, separator=" "):
        """
        Get the current interval in words in the current locale.

        Ex: 6 jours 23 heures 58 minutes

        :param locale: The locale to use. Defaults to current locale.
        :type locale: str

        :param separator: The separator to use between each unit
        :type separator: str

        :rtype: str
        """
        periods = [
            ("year", self.years),
            ("month", self.months),
            ("week", self.weeks),
            ("day", self.remaining_days),
            ("hour", self.hours),
            ("minute", self.minutes),
            ("second", self.remaining_seconds),
        ]

        if locale is None:
            locale = pendulum.get_locale()

        locale = pendulum.locale(locale)
        parts = []
        for period in periods:
            unit, count = period
            if abs(count) > 0:
                translation = locale.translation(
                    "units.{}.{}".format(unit, locale.plural(abs(count)))
                )
                parts.append(translation.format(count))

        if not parts and abs(self.microseconds) > 0:
            translation = locale.translation("units.second.{}".format(locale.plural(1)))
            us = abs(self.microseconds) / 1e6
            parts.append(translation.format("{:.2f}").format(us))

        return decode(separator.join(parts))