Exemple #1
0
def format_datetime(t=None, format='%x %X', tzinfo=None, locale=None):
    """Format the `datetime` object `t` into an `unicode` string

    If `t` is None, the current time will be used.
    
    The formatting will be done using the given `format`, which consist
    of conventional `strftime` keys. In addition the format can be 'iso8601'
    to specify the international date format (compliant with RFC 3339).

    `tzinfo` will default to the local timezone if left to `None`.
    """
    if locale == 'iso8601':
        format = _ISO8601_FORMATS['datetime'].get(format, format)
        return _format_datetime_without_babel(t, format, tzinfo)
    if babel and locale:
        if format == '%x':
            return babel_format_date(t, 'medium', locale)
        if format == '%X':
            t = to_datetime(t, tzinfo)
            return babel_format_time(t, 'medium', None, locale)
        if format in ('%x %X', None):
            format = 'medium'
        if format in _BABEL_FORMATS['datetime']:
            t = to_datetime(t, tzinfo)
            return babel_format_datetime(t, format, None, locale)
    format = _BABEL_FORMATS['datetime'].get(format, format)
    return _format_datetime_without_babel(t, format, tzinfo)
Exemple #2
0
def format_datetime(t=None, format='%x %X', tzinfo=None, locale=None):
    """Format the `datetime` object `t` into an `unicode` string

    If `t` is None, the current time will be used.
    
    The formatting will be done using the given `format`, which consist
    of conventional `strftime` keys. In addition the format can be 'iso8601'
    to specify the international date format (compliant with RFC 3339).

    `tzinfo` will default to the local timezone if left to `None`.
    """
    if locale == 'iso8601':
        format = _ISO8601_FORMATS['datetime'].get(format, format)
        return _format_datetime_without_babel(t, format, tzinfo)
    if babel and locale:
        if format == '%x':
            return babel_format_date(t, 'medium', locale)
        if format == '%X':
            t = to_datetime(t, tzinfo)
            return babel_format_time(t, 'medium', None, locale)
        if format in ('%x %X', None):
            format = 'medium'
        if format in _BABEL_FORMATS['datetime']:
            t = to_datetime(t, tzinfo)
            return babel_format_datetime(t, format, None, locale)
    format = _BABEL_FORMATS['datetime'].get(format, format)
    return _format_datetime_without_babel(t, format, tzinfo)
Exemple #3
0
def _format_datetime(t, format, tzinfo, locale, hint):
    t = to_datetime(t, tzinfo or localtz)

    if format == 'iso8601':
        return _format_datetime_iso8601(t, 'long', hint)
    if format in ('iso8601date', 'iso8601time'):
        return _format_datetime_iso8601(t, 'long', format[7:])
    if locale == 'iso8601':
        if format is None:
            format = 'long'
        elif format in _STRFTIME_HINTS:
            hint = _STRFTIME_HINTS[format]
            format = 'long'
        if format in ('short', 'medium', 'long', 'full'):
            return _format_datetime_iso8601(t, format, hint)
        return _format_datetime_without_babel(t, format)

    if babel and locale:
        if format is None:
            format = 'medium'
        elif format in _STRFTIME_HINTS:
            hint = _STRFTIME_HINTS[format]
            format = 'medium'
        if format in ('short', 'medium', 'long', 'full'):
            if hint == 'datetime':
                return babel_format_datetime(t, format, None, locale)
            if hint == 'date':
                return babel_format_date(t, format, locale)
            if hint == 'time':
                return babel_format_time(t, format, None, locale)

    format = _BABEL_FORMATS[hint].get(format, format)
    return _format_datetime_without_babel(t, format)
Exemple #4
0
def _format_datetime(t, format, tzinfo, locale, hint):
    t = to_datetime(t, tzinfo or localtz)

    if format == 'iso8601':
        return _format_datetime_iso8601(t, 'long', hint)
    if format in ('iso8601date', 'iso8601time'):
        return _format_datetime_iso8601(t, 'long', format[7:])
    if locale == 'iso8601':
        if format is None:
            format = 'long'
        elif format in _STRFTIME_HINTS:
            hint = _STRFTIME_HINTS[format]
            format = 'long'
        if format in ('short', 'medium', 'long', 'full'):
            return _format_datetime_iso8601(t, format, hint)
        return _format_datetime_without_babel(t, format)

    if babel and locale:
        if format is None:
            format = 'medium'
        elif format in _STRFTIME_HINTS:
            hint = _STRFTIME_HINTS[format]
            format = 'medium'
        if format in ('short', 'medium', 'long', 'full'):
            if hint == 'datetime':
                return babel_format_datetime(t, format, None, locale)
            if hint == 'date':
                return babel_format_date(t, format, locale)
            if hint == 'time':
                return babel_format_time(t, format, None, locale)

    format = _BABEL_FORMATS[hint].get(format, format)
    return _format_datetime_without_babel(t, format)
Exemple #5
0
def _format_html_time_tag(datetime, what_to_display):
    now = time_utcnow()

    date = None
    if datetime.date() == now.date():
        date = "Today"
    elif datetime.date() == (now - timedelta(days=1)).date():
        date = "Yesterday"

    if what_to_display == "date-only":
        exact = babel_format_date(datetime, format="dd MMM yyyy", locale=_get_user_locale())
        content = date if date else exact
    elif what_to_display == "date-and-time":
        exact = babel_format_datetime(
                    datetime, format="dd.MM.yyyy HH:mm:ss", tzinfo=get_timezone(), locale=_get_user_locale()
                )

        if date:
            content = date + ", " + \
                babel_format_datetime(
                    datetime, format="HH:mm:ss", tzinfo=get_timezone(), locale=_get_user_locale()
                )
        else:
            content = exact
    else:
        raise ValueError("what_to_display argument invalid")

    isoformat = datetime.isoformat()

    return Markup('<time datetime="{isoformat}" data-toggle="tooltip" data-placement="top" title="{exact}">{content}</time>'.format(
            isoformat=isoformat, exact=exact, content=content
        ))
Exemple #6
0
def format_date(dt, locale_name=None, format="medium"):
    """Returns a prettyfied version of a date. If a locale_name is
    provided the date will be localized. Without a locale the
    datetime will be formatted into the form YYYY-MM-DD hh:ss"""
    if locale_name:
        locale = Locale(locale_name)
        return babel_format_date(dt, locale=locale, format=format)
    return dt.strftime("%Y-%m-%d")
Exemple #7
0
def format_date(dt, locale_name=None, format="medium"):
    """Returns a prettyfied version of a date. If a locale_name is
    provided the date will be localized. Without a locale the
    datetime will be formatted into the form YYYY-MM-DD hh:ss"""
    if locale_name:
        locale = Locale(locale_name)
        return babel_format_date(dt, locale=locale, format=format)
    return dt.strftime("%Y-%m-%d")
Exemple #8
0
def format_date(value, format='medium'):
    """Parse a date object or string using dateutil and return a pt_PT
    localized string using babel."""
    from babel.dates import format_date as babel_format_date
    import datetime
    if not value:
        return None
    from dateutil import parser as dateparser
    if type(value) not in (datetime.date, datetime.datetime):
        value = dateparser.parse(value)
    return babel_format_date(value, format, locale="pt_PT")
Exemple #9
0
def format_date(mp, locale):
    """Format a MakoParsable object as a date in provided locale

    Usage
    =====

    Let's create two MakoParsable date:

        >>> epoch_datetime = MakoParsable(datetime.utcfromtimestamp(0))
        >>> epoch_string = MakoParsable("2000-10-10")

    ``format_date`` should convert to the accurate human local representation
    of these date:

        >>> format_date(epoch_datetime, "fr")
        u'1 janvier 1970'
        >>> format_date(epoch_string, "fr")
        u'10 octobre 2000'

    Acceptance of both format is required for conveniency as OOOP object and
    OpenERP object do not behave the same way when accessing datetime objects.

    Please note that providing a non-string / date object will result by
    returning a MakoParsable(None):

        >>> format_date(MakoParsable(2), "fr")
        None
        >>> type(format_date(MakoParsable(2), "fr"))  # doctest: +ELLIPSIS
        <class '...MakoParsable'>

    Please note that other languages are supported:

        >>> format_date(epoch_string, "en")
        u'October 10, 2000'
        >>> format_date(epoch_string, "de")
        u'10. Oktober 2000'

    """
    if not isinstance(mp, MakoParsable):
        raise TypeError("Argument %r is not a MakoParsable." % mp)

    raw = getattr(mp, "_obj")

    if isinstance(raw, basestring):
        dt = datetime.strptime(raw, "%Y-%m-%d")
    elif isinstance(raw, datetime) or isinstance(raw, date):
        dt = raw
    else:
        return MakoParsable(None)
    return MakoParsable(babel_format_date(dt,
                                          format="long",
                                          locale=locale))
Exemple #10
0
 def format_datetime(self, datetime_obj, date_only, format,
                     localized) -> str:
     if date_only:
         return babel_format_date(datetime_obj,
                                  format=format,
                                  locale=self.locale)
     else:
         if localized:
             tzinfo = get_localzone()
         else:
             tzinfo = None
         return babel_format_datetime(datetime_obj,
                                      format=format,
                                      tzinfo=tzinfo,
                                      locale=self.locale)
Exemple #11
0
def _format_html_time_tag(datetime, what_to_display):
    if what_to_display == "date-only":
        content = babel_format_date(datetime,
                                    format="dd MMM yyyy",
                                    locale=_get_user_locale())
    elif what_to_display == "date-and-time":
        content = babel_format_datetime(datetime,
                                        format="dd.MM.yyyy HH:mm:ss",
                                        tzinfo=get_timezone("Europe/Moscow"),
                                        locale=_get_user_locale())
    else:
        raise ValueError("what_to_display argument invalid")

    isoformat = datetime.isoformat()

    return Markup('<time datetime="{}">{}</time>'.format(isoformat, content))
Exemple #12
0
def format_date(d, format='medium'):
    """Return the given date `d` formatted with `Babel's date formatting
    <http://babel.edgewall.org/wiki/Documentation/dates.html>`_ and
    using Django's current language.

    """
    if not d:
        return ''
    if isinstance(d, IncompleteDate):
        d = d.as_date()
    if not isinstance(d, datetime.date):
        raise Exception("Not a date: {0!r}".format(d))
    lng = translation.get_language()
    if lng is None:  # occured during syncdb
        lng = settings.SITE.languages[0].django_code
    return babel_format_date(d, format=format, locale=to_locale(lng))
Exemple #13
0
def format_date(t=None, format='%x', tzinfo=None, locale=None):
    """Convenience method for formatting the date part of a `datetime` object.
    See `format_datetime` for more details.
    """
    if locale == 'iso8601':
        format = _ISO8601_FORMATS['date'].get(format, format)
        return _format_datetime_without_babel(t, format, tzinfo)
    if format == 'iso8601':
        format = 'iso8601date'
    if babel and locale:
        if format in ('%x', None):
            format = 'medium'
        if format in _BABEL_FORMATS['date']:
            t = to_datetime(t, tzinfo)
            return babel_format_date(t, format, locale)
    format = _BABEL_FORMATS['date'].get(format, format)
    return _format_datetime_without_babel(t, format, tzinfo)
Exemple #14
0
def format_date(t=None, format='%x', tzinfo=None, locale=None):
    """Convenience method for formatting the date part of a `datetime` object.
    See `format_datetime` for more details.
    """
    if locale == 'iso8601':
        format = _ISO8601_FORMATS['date'].get(format, format)
        return _format_datetime_without_babel(t, format, tzinfo)
    if format == 'iso8601':
        format = 'iso8601date'
    if babel and locale:
        if format in ('%x', None):
            format = 'medium'
        if format in _BABEL_FORMATS['date']:
            t = to_datetime(t, tzinfo)
            return babel_format_date(t, format, locale)
    format = _BABEL_FORMATS['date'].get(format, format)
    return _format_datetime_without_babel(t, format, tzinfo)
Exemple #15
0
def _format_html_time_tag(datetime, what_to_display):
    if what_to_display == "date-only":
        content = babel_format_date(datetime, locale=_get_user_locale())
    elif what_to_display == "date-and-time":
        content = babel_format_datetime(datetime,
                                        tzinfo=UTC,
                                        locale=_get_user_locale())
        # While this could be done with a format string, that would
        # hinder internationalization and honestly why bother.
        content += " UTC"
    else:
        raise ValueError("what_to_display argument invalid")

    isoformat = datetime.isoformat()

    return Markup(
        '<time datetime="{}" data-what_to_display="{}">{}</time>'.format(
            isoformat, what_to_display, content))
Exemple #16
0
def _format_html_time_tag(datetime, what_to_display):
    if what_to_display == "date-only":
        content = babel_format_date(datetime, locale=_get_user_locale())
    elif what_to_display == "date-and-time":
        content = babel_format_datetime(
            datetime, tzinfo=UTC, locale=_get_user_locale()
        )
        # While this could be done with a format string, that would
        # hinder internationalization and honestly why bother.
        content += " UTC"
    else:
        raise ValueError("what_to_display argument invalid")

    isoformat = datetime.isoformat()

    return Markup(
        '<time datetime="{}" data-what_to_display="{}">{}</time>'.format(
            isoformat, what_to_display, content
        )
    )
Exemple #17
0
def format_date(d, format='medium'):
    """Return the given date `d` formatted with `Babel's date formatting
    <http://babel.edgewall.org/wiki/Documentation/dates.html>`_ and
    using Django's current language.

    """
    if not d:
        return ''
    if isinstance(d, IncompleteDate):
        d = d.as_date()
    if not isinstance(d, datetime.date):
        if isinstance(d, six.text_type):
            d = str(d)  # remove the "u" in Python 2
        raise Exception(str("Not a date: {0!r}").format(d))
    lng = translation.get_language()
    if lng is None:  # occured during syncdb
        lng = settings.SITE.languages[0].django_code
    loc = to_locale(lng)
    if loc == 'en':
        loc = 'en_UK'  # I hate US date format
    return babel_format_date(d, format=format, locale=loc)
Exemple #18
0
def format_date(d, format='medium'):
    """Return the given date `d` formatted with `Babel's date formatting
    <http://babel.edgewall.org/wiki/Documentation/dates.html>`_ and
    using Django's current language.

    """
    if not d:
        return ''
    if isinstance(d, IncompleteDate):
        d = d.as_date()
    if not isinstance(d, datetime.date):
        if isinstance(d, six.text_type):
            d = str(d)  # remove the "u" in Python 2
        raise Exception(str("Not a date: {0!r}").format(d))
    lng = translation.get_language()
    if lng is None:  # occured during syncdb
        lng = settings.SITE.languages[0].django_code
    loc = to_locale(lng)
    if loc == 'en':
        loc = 'en_UK'  # I hate US date format
    return babel_format_date(d, format=format, locale=loc)
Exemple #19
0
def format_date(date=None, format='medium', locale=None):
    if locale:
        return babel_format_date(date=date, format=format, locale=locale)
    else:
        return str(date)
def format_date(date=None, format='medium', locale=None):
    if locale:
        return babel_format_date(date=date, format=format, locale=locale)
    else:
        return str(date)
def format_date(value, format='medium'):
    if type(value) not in (datetime.date, datetime.datetime):
        log.error(type(value))
        value = dateparser.parse(value)
    return babel_format_date(value, format, locale="pt_PT")
Exemple #22
0
def format_date(value, request, date_format='long'):
    localizer = get_localizer(request)
    return babel_format_date(value, date_format, locale=localizer.locale_name)
Exemple #23
0
def format_date(value: date, format: str = "long") -> str:
    return babel_format_date(value, format=format)
Exemple #24
0
def format_date(d, format='medium'):
    if not d:
        return ''
    return babel_format_date(d, format=format,
                             locale=to_locale(translation.get_language()))