Exemplo n.º 1
0
def datetimeformat(context, value, format='shortdatetime'):
    """
    Returns a formatted date/time using Babel's locale settings. Uses the
    timezone from settings.py, if the user has not been authenticated.
    """
    if not isinstance(value, datetime.datetime):
        # Expecting date value
        raise ValueError

    request = context.get('request')

    default_tzinfo = convert_tzinfo = timezone(settings.TIME_ZONE)
    if value.tzinfo is None:
        value = default_tzinfo.localize(value)
        new_value = value.astimezone(default_tzinfo)
    else:
        new_value = value

    if 'timezone' not in request.session:
        if request.user.is_authenticated():
            try:
                convert_tzinfo = request.user.get_profile().timezone or \
                                 default_tzinfo
            except (Profile.DoesNotExist, AttributeError):
                pass
        request.session['timezone'] = convert_tzinfo
    else:
        convert_tzinfo = request.session['timezone']

    convert_value = new_value.astimezone(convert_tzinfo)
    locale = _babel_locale(_contextual_locale(context))

    # If within a day, 24 * 60 * 60 = 86400s
    if format == 'shortdatetime':
        # Check if the date is today
        today = datetime.datetime.now(tz=convert_tzinfo).toordinal()
        if convert_value.toordinal() == today:
            formatted = _lazy(u'Today at %s') % format_time(
                convert_value, format='short', tzinfo=convert_tzinfo,
                locale=locale)
        else:
            formatted = format_datetime(convert_value, format='short',
                tzinfo=convert_tzinfo, locale=locale)
    elif format == 'longdatetime':
        formatted = format_datetime(convert_value, format='long',
            tzinfo=convert_tzinfo, locale=locale)
    elif format == 'date':
        formatted = format_date(convert_value, locale=locale)
    elif format == 'time':
        formatted = format_time(convert_value, tzinfo=convert_tzinfo,
            locale=locale)
    elif format == 'datetime':
        formatted = format_datetime(convert_value, tzinfo=convert_tzinfo,
            locale=locale)
    else:
        # Unknown format
        raise DateTimeFormatError

    return jinja2.Markup('<time datetime="%s">%s</time>' % \
                         (convert_value.isoformat(), formatted))
Exemplo n.º 2
0
def datetimeformat(context, value, format='shortdatetime'):
    """
    Returns date/time formatted using babel's locale settings. Uses the
    timezone from settings.py
    """
    if not isinstance(value, datetime.datetime):
        # Expecting date value
        raise ValueError

    tzinfo = timezone(settings.TIME_ZONE)
    tzvalue = tzinfo.localize(value)
    locale = _babel_locale(_contextual_locale(context))

    # If within a day, 24 * 60 * 60 = 86400s
    if format == 'shortdatetime':
        # Check if the date is today
        if value.toordinal() == datetime.date.today().toordinal():
            formatted = _lazy(u'Today at %s') % format_time(
                                    tzvalue, format='short', locale=locale)
        else:
            formatted = format_datetime(tzvalue, format='short', locale=locale)
    elif format == 'longdatetime':
        formatted = format_datetime(tzvalue, format='long', locale=locale)
    elif format == 'date':
        formatted = format_date(tzvalue, locale=locale)
    elif format == 'time':
        formatted = format_time(tzvalue, locale=locale)
    elif format == 'datetime':
        formatted = format_datetime(tzvalue, locale=locale)
    else:
        # Unknown format
        raise DateTimeFormatError

    return jinja2.Markup('<time datetime="%s">%s</time>' % \
                         (tzvalue.isoformat(), formatted))
Exemplo n.º 3
0
def test_no_inherit_metazone_formatting():
    # See: https://github.com/python-babel/babel/issues/428
    tz = pytz.timezone('America/Los_Angeles')
    t = tz.localize(datetime(2016, 1, 6, 7))
    assert dates.format_time(t, format='long', locale='en_US') == "7:00:00 AM PST"
    assert dates.format_time(t, format='long', locale='en_GB') == "07:00:00 Pacific Standard Time"
    assert dates.get_timezone_name(t, width='short', locale='en_US') == "PST"
    assert dates.get_timezone_name(t, width='short', locale='en_GB') == "Pacific Standard Time"
Exemplo n.º 4
0
    def test_format_time(self):
        import datetime
        from babel.dates import format_time
        from babel.core import UnknownLocaleError

        api = self.make()
        first = datetime.time(23, 59)
        self.assertEqual(api.format_time(first), format_time(first, format="medium", locale="en"))
        self.assertEqual(api.format_time(first, format="short"), format_time(first, format="short", locale="en"))
        api.locale_name = "unknown"
        self.assertRaises(UnknownLocaleError, api.format_time, first)
Exemplo n.º 5
0
def datetimeformat(context, value, format="shortdatetime"):
    """
    Returns a formatted date/time using Babel's locale settings. Uses the
    timezone from settings.py, if the user has not been authenticated.
    """
    if not isinstance(value, datetime.datetime):
        # Expecting date value
        raise ValueError("Unexpected value {value} passed to datetimeformat".format(value=value))

    request = context.get("request")

    default_tzinfo = convert_tzinfo = timezone(settings.TIME_ZONE)
    if value.tzinfo is None:
        value = default_tzinfo.localize(value)
        new_value = value.astimezone(default_tzinfo)
    else:
        new_value = value

    if "timezone" not in request.session:
        if request.user.is_authenticated():
            try:
                convert_tzinfo = Profile.objects.get(user=request.user).timezone or default_tzinfo
            except (Profile.DoesNotExist, AttributeError):
                pass
        request.session["timezone"] = convert_tzinfo
    else:
        convert_tzinfo = request.session["timezone"]

    convert_value = new_value.astimezone(convert_tzinfo)
    locale = _babel_locale(_contextual_locale(context))

    # If within a day, 24 * 60 * 60 = 86400s
    if format == "shortdatetime":
        # Check if the date is today
        today = datetime.datetime.now(tz=convert_tzinfo).toordinal()
        if convert_value.toordinal() == today:
            formatted = _lazy(u"Today at %s") % format_time(
                convert_value, format="short", tzinfo=convert_tzinfo, locale=locale
            )
        else:
            formatted = format_datetime(convert_value, format="short", tzinfo=convert_tzinfo, locale=locale)
    elif format == "longdatetime":
        formatted = format_datetime(convert_value, format="long", tzinfo=convert_tzinfo, locale=locale)
    elif format == "date":
        formatted = format_date(convert_value, locale=locale)
    elif format == "time":
        formatted = format_time(convert_value, tzinfo=convert_tzinfo, locale=locale)
    elif format == "datetime":
        formatted = format_datetime(convert_value, tzinfo=convert_tzinfo, locale=locale)
    else:
        # Unknown format
        raise DateTimeFormatError

    return jinja2.Markup('<time datetime="%s">%s</time>' % (convert_value.isoformat(), formatted))
Exemplo n.º 6
0
def datetimeformat(context, value, format='shortdatetime', output='html'):
    """
    Returns date/time formatted using babel's locale settings. Uses the
    timezone from settings.py
    """
    if not isinstance(value, datetime.datetime):
        if isinstance(value, datetime.date):
            # Turn a date into a datetime
            value = datetime.datetime.combine(value,
                                              datetime.datetime.min.time())
        else:
            # Expecting datetime value
            raise ValueError

    default_tz = timezone(settings.TIME_ZONE)
    tzvalue = default_tz.localize(value)

    user = context['request'].user
    try:
        profile = user.get_profile()
        if user.is_authenticated() and profile.timezone:
            user_tz = profile.timezone
            tzvalue = user_tz.normalize(tzvalue.astimezone(user_tz))
    except AttributeError:
        pass

    locale = _babel_locale(_contextual_locale(context))

    # If within a day, 24 * 60 * 60 = 86400s
    if format == 'shortdatetime':
        # Check if the date is today
        if value.toordinal() == datetime.date.today().toordinal():
            formatted = _lazy(u'Today at %s') % format_time(
                tzvalue, format='short', locale=locale)
        else:
            formatted = format_datetime(tzvalue, format='short', locale=locale)
    elif format == 'longdatetime':
        formatted = format_datetime(tzvalue, format='long', locale=locale)
    elif format == 'date':
        formatted = format_date(tzvalue, locale=locale)
    elif format == 'time':
        formatted = format_time(tzvalue, locale=locale)
    elif format == 'datetime':
        formatted = format_datetime(tzvalue, locale=locale)
    else:
        # Unknown format
        raise DateTimeFormatError

    if output == 'json':
        return formatted
    return jinja2.Markup('<time datetime="%s">%s</time>' %
                         (tzvalue.isoformat(), formatted))
Exemplo n.º 7
0
 def test_format_time(self, db_session):
     import datetime
     from babel.dates import format_time
     from babel.core import UnknownLocaleError
     api = self.make()
     first = datetime.time(23, 59)
     assert (
         api.format_time(first) ==
         format_time(first, format='medium', locale='en'))
     assert (
         api.format_time(first, fmt='short') ==
         format_time(first, format='short', locale='en'))
     api.locale_name = 'unknown'
     with raises(UnknownLocaleError):
         api.format_time(first)
Exemplo n.º 8
0
def pretty_time(dt):
    display_tz = pytz.timezone(c.liveupdate_event.timezone)
    today = datetime.datetime.now(display_tz).date()
    date = dt.astimezone(display_tz).date()

    if date == today:
        return format_time(
            time=dt,
            tzinfo=display_tz,
            format="HH:mm z",
            locale=c.locale,
        )
    elif today - date < datetime.timedelta(days=365):
        return format_datetime(
            datetime=dt,
            tzinfo=display_tz,
            format="dd MMM HH:mm z",
            locale=c.locale,
        )
    else:
        return format_datetime(
            datetime=dt,
            tzinfo=display_tz,
            format="dd MMM YYYY HH:mm z",
            locale=c.locale,
        )
Exemplo n.º 9
0
    def format_time(self, t=None, format='medium'):
        """Return a time formatted according to the given pattern

        >>> t = datetime.time(15, 30)
        >>> Locale('en', 'US').format_time(t)
        u'3:30:00 PM'
        >>> Locale('de', 'DE').format_time(t, format='short')
        u'15:30'

        If you don't want to use the locale default formats, you can specify a
        custom time pattern:

        >>> Locale('en').format_time(t, "hh 'o''clock' a")
        u"03 o'clock PM"

        In:
          - ``t`` --  ``time`` or ``datetime`` object; if `None`, the current time in UTC is used
          - ``format`` -- 'full', 'long', 'medium', or 'short', or a custom date/time pattern

        Returns:
          - the formatted time string
        """
        if isinstance(t, datetime.time):
            d = datetime.datetime.now()
            t = d.replace(hour=t.hour, minute=t.minute, second=t.second)

        if isinstance(t, datetime.datetime):
            t = self.to_utc(t)

        return dates.format_time(t, format, locale=self, tzinfo=self.tzinfo)
Exemplo n.º 10
0
 def asString(self, objValue, objType):
     '''
     @see: Converter.asString
     '''
     assert isinstance(objType, Type), 'Invalid object type %s' % objType
     if isinstance(objType, TypeModel): # If type model is provided we consider the model property type
         assert isinstance(objType, TypeModel)
         container = objType.container
         assert isinstance(container, Model)
         objType = container.properties[container.propertyId]
     if objType.isOf(str):
         return objValue
     if objType.isOf(bool):
         return str(objValue)
     if objType.isOf(Percentage):
         return bn.format_percent(objValue, self.formats.get(Percentage, None), self.locale)
     if objType.isOf(Number):
         return bn.format_decimal(objValue, self.formats.get(Number, None), self.locale)
     if objType.isOf(Date):
         return bd.format_date(objValue, self.formats.get(Date, None), self.locale)
     if objType.isOf(Time):
         return bd.format_time(objValue, self.formats.get(Time, None), self.locale)
     if objType.isOf(DateTime):
         return bd.format_datetime(objValue, self.formats.get(DateTime, None), None, self.locale)
     raise TypeError('Invalid object type %s for Babel converter' % objType)
Exemplo n.º 11
0
    def format_time(self, time=None, format=None, rebase=True):
        """Returns a time formatted according to the given pattern and
        following the current locale and timezone.

        :param time:
            A ``time`` or ``datetime`` object. If None, the current
            time in UTC is used.
        :param format:
            The format to be returned. Valid values are "short", "medium",
            "long", "full" or a custom date/time pattern. Example outputs:

            - short:  4:36 PM
            - medium: 4:36:05 PM
            - long:   4:36:05 PM +0000
            - full:   4:36:05 PM World (GMT) Time

        :param rebase:
            If True, converts the time to the current :attr:`timezone`.
        :returns:
            A formatted time in unicode.
        """
        format = self._get_format('time', format)

        kwargs = {}
        if rebase:
            kwargs['tzinfo'] = self.tzinfo

        return dates.format_time(time, format, locale=self.locale, **kwargs)
Exemplo n.º 12
0
def localize_timestamp(timestamp, user):
    try:
        user_timezone = dates.get_timezone(user.timezone)
    except LookupError:
        user_timezone = dates.get_timezone('Etc/UTC')

    try:
        user_locale = Locale(user.locale)
    except core.UnknownLocaleError:
        user_locale = Locale('en')

    # Do our best to find a valid locale
    try:
        user_locale.date_formats
    except IOError:  # An IOError will be raised if locale's casing is incorrect, e.g. de_de vs. de_DE
        # Attempt to fix the locale, e.g. de_de -> de_DE
        try:
            user_locale = Locale(fix_locale(user.locale))
            user_locale.date_formats
        except (core.UnknownLocaleError, IOError):
            user_locale = Locale('en')

    formatted_date = dates.format_date(timestamp, format='full', locale=user_locale)
    formatted_time = dates.format_time(timestamp, format='short', tzinfo=user_timezone, locale=user_locale)

    return u'{time} on {date}'.format(time=formatted_time, date=formatted_date)
Exemplo n.º 13
0
 def test_format_time(self):
     import datetime
     from babel.dates import format_time
     from babel.core import UnknownLocaleError
     api = self._make()
     first = datetime.time(23, 59)
     self.assertEqual(
         api.format_time(first),
         format_time(first, format='medium', locale='en'),
     )
     self.assertEqual(
         api.format_time(first, format='short'),
         format_time(first, format='short', locale='en'),
     )
     api.locale_name = 'unknown'
     self.assertRaises(UnknownLocaleError, api.format_time, first)
Exemplo n.º 14
0
def test_smoke_dates(locale):
    locale = Locale.parse(locale)
    instant = datetime.now()
    for width in ("full", "long", "medium", "short"):
        assert dates.format_date(instant, format=width, locale=locale)
        assert dates.format_datetime(instant, format=width, locale=locale)
        assert dates.format_time(instant, format=width, locale=locale)
Exemplo n.º 15
0
 def test_time(self):
     """Expects time format."""
     value_test = datetime.fromordinal(733900)
     value_expected = format_time(value_test, locale=u'en_US')
     value_returned = datetimeformat(self.context, value_test,
                                     format='time')
     eq_(pq(value_returned)('time').text(), value_expected)
Exemplo n.º 16
0
 def __mod__(self, fmt):
     try:
         return format_time(self.time,
                            fmt,
                            locale=text_type(pilot.context.get('.locale', 'en_US')))
     except:
         raise ValueError("'{}' is not a valid time format string".format(fmt))
Exemplo n.º 17
0
def format_time(time=None, format=None, locale=None, timezone=None,
    rebase=True):
    """Returns a time formatted according to the given pattern and following
    the current locale and timezone.

    :param time:
        A ``time`` or ``datetime`` object. If None, the current
        time in UTC is used.
    :param format:
        The format to be returned. Valid values are "short", "medium",
        "long", "full" or a custom date/time pattern. Example outputs:

        - short:  4:36 PM
        - medium: 4:36:05 PM
        - long:   4:36:05 PM +0000
        - full:   4:36:05 PM World (GMT) Time

    :param locale:
        A locale code. If not set, uses the currently loaded locale.
    :param timezone:
        The timezone name from the Olson database, e.g.: ``America/Chicago``.
        If not set, uses the default returned by :func:`get_timezone`.
    :param rebase:
        If True, converts the time to the currently loaded timezone.
    :returns:
        A formatted time in unicode.
    """
    format = _get_format('time', format)
    locale = locale or get_locale()

    kwargs = {}
    if rebase:
        kwargs['tzinfo'] = get_timezone(timezone)

    return dates.format_time(time, format, locale=locale, **kwargs)
Exemplo n.º 18
0
 def test_time(self):
     """Expects time format."""
     value_test = datetime.fromordinal(733900)
     value_expected = format_time(value_test, locale='en_US')
     value_returned = datetimeformat(self.context, value_test,
                                     format='time',
                                     output='json')
     assert value_expected == value_returned
Exemplo n.º 19
0
def format_time(t, request):
	if t is None:
		return ''
	if not isinstance(t, (datetime, time)):
		return t

	l = get_locale(request)
	return dates.format_time(t, locale=l)
Exemplo n.º 20
0
 def test_today(self):
     """Expects shortdatetime, format: Today at {time}."""
     date_today = datetime.today()
     value_returned = unicode(datetimeformat(self.context, date_today))
     value_expected = 'Today at %s' % format_time(date_today,
                                                  format='short',
                                                  locale=u'en_US')
     eq_(pq(value_returned)('time').text(), value_expected)
Exemplo n.º 21
0
    def test_format_time(self, db_session):
        import datetime
        from babel.dates import format_time
        from babel.core import UnknownLocaleError

        api = self.make()
        first = datetime.time(23, 59)
        assert api.format_time(first) == format_time(
            first, format="medium", locale="en"
        )
        assert api.format_time(first, fmt="short") == format_time(
            first, format="short", locale="en"
        )
        # noinspection PyPropertyAccess
        api.locale_name = "unknown"
        with raises(UnknownLocaleError):
            api.format_time(first)
def test_format_time():
    t = time(15, 30)
    assert dates.format_time(t, locale='en_US') == u'3:30:00 PM'
    assert dates.format_time(t, format='short', locale='de_DE') == u'15:30'

    assert (dates.format_time(t, "hh 'o''clock' a",
                              locale='en') == u"03 o'clock PM")

    t = datetime(2007, 4, 1, 15, 30)
    tzinfo = timezone('Europe/Paris')
    t = tzinfo.localize(t)
    fr = dates.format_time(t, format='full', tzinfo=tzinfo, locale='fr_FR')
    assert fr == u'15:30:00 heure d\u2019\xe9t\xe9 d\u2019Europe centrale'
    custom = dates.format_time(t,
                               "hh 'o''clock' a, zzzz",
                               tzinfo=timezone('US/Eastern'),
                               locale='en')
    assert custom == u"09 o'clock AM, Eastern Daylight Time"

    t = time(15, 30)
    paris = dates.format_time(t,
                              format='full',
                              tzinfo=timezone('Europe/Paris'),
                              locale='fr_FR')
    assert paris == u'15:30:00 heure normale d\u2019Europe centrale'
    us_east = dates.format_time(t,
                                format='full',
                                tzinfo=timezone('US/Eastern'),
                                locale='en_US')
    assert us_east == u'3:30:00 PM Eastern Standard Time'
Exemplo n.º 23
0
 def test_today(self):
     """Expects shortdatetime, format: Today at {time}."""
     date_today = datetime.today()
     value_expected = 'Today at %s' % format_time(date_today,
                                                  format='short',
                                                  locale='en_US')
     value_returned = datetimeformat(self.context, date_today,
                                     output='json')
     assert value_expected == value_returned
Exemplo n.º 24
0
 def test_time(self):
     """Expects time format."""
     value_test = datetime.fromordinal(733900)
     value_localize = self.timezone.localize(value_test)
     value_expected = format_time(value_localize, locale=self.locale,
                                  tzinfo=self.timezone)
     value_returned = datetimeformat(self.context, value_test,
                                     format='time')
     eq_(pq(value_returned)('time').text(), value_expected)
Exemplo n.º 25
0
def timeformat(value, format="medium", locale=None):
    if value is None:
        return ""

    if locale is None:
        locale = to_locale(settings.LANGUAGE_CODE)

    parsed_value = parse_string(value)
    return format_time(parsed_value, format, locale=locale)
Exemplo n.º 26
0
 def test_today(self):
     """Expects shortdatetime, format: Today at {time}."""
     date_today = datetime.today()
     value_expected = "Today at %s" % format_time(
         date_today, format="short", locale="en_US")
     value_returned = datetimeformat(self.context,
                                     date_today,
                                     output="json")
     assert value_expected == value_returned
Exemplo n.º 27
0
def format_time(time=None, format='medium'):
    """Returns a time formated according to the given format in the context
    of current locale. If `time` is None, current time is assumed.

    :param time: an instance of :class:`~datetime.time` or None
    :param format: format pattern, one of `short`, `medium`, `long` or `full`.
    :returns: formated time as string
    """
    return dates.format_time(time, format=format, locale=get_locale())
Exemplo n.º 28
0
def localize_time(obj, locale, format=None, **kwargs):
    """TODO
    
    :param obj: TODO
    :param locale: the current locale (e.g: en, en_us, it)
    :param format: TODO"""
    format = format or 'short'
    dt = datetime.datetime(1970, 1, 1, obj.hour, obj.minute, obj.second, obj.microsecond, obj.tzinfo)
    return dates.format_time(obj, format=format, locale=locale)
Exemplo n.º 29
0
 def test_time(self):
     """Expects time format."""
     value_test = datetime.fromordinal(733900)
     value_expected = format_time(value_test, locale='en_US')
     value_returned = datetimeformat(self.context,
                                     value_test,
                                     format='time',
                                     output='json')
     assert value_expected == value_returned
Exemplo n.º 30
0
 def test_today(self):
     """Expects shortdatetime, format: Today at {time}."""
     date_today = datetime.today()
     date_localize = self.timezone.localize(date_today)
     value_returned = str(datetimeformat(self.context, date_today))
     value_expected = "Today at %s" % format_time(
         date_localize, format="short", locale=self.locale, tzinfo=self.timezone
     )
     eq_(pq(value_returned)("time").text(), value_expected)
Exemplo n.º 31
0
 def __mod__(self, fmt):
     try:
         return format_time(self.time,
                            fmt,
                            locale=text_type(
                                pilot.context.get('.locale', 'en_US')))
     except:
         raise ValueError(
             "'{}' is not a valid time format string".format(fmt))
Exemplo n.º 32
0
    def test_format_time(self, db_session):
        import datetime
        from babel.dates import format_time
        from babel.core import UnknownLocaleError

        api = self.make()
        first = datetime.time(23, 59)
        assert api.format_time(first) == format_time(first,
                                                     format="medium",
                                                     locale="en")
        assert api.format_time(first,
                               fmt="short") == format_time(first,
                                                           format="short",
                                                           locale="en")
        # noinspection PyPropertyAccess
        api.locale_name = "unknown"
        with raises(UnknownLocaleError):
            api.format_time(first)
Exemplo n.º 33
0
 def test_today(self):
     """Expects shortdatetime, format: Today at {time}."""
     date_today = datetime.today()
     value_expected = 'Today at %s' % format_time(
         date_today, format='short', locale='en_US')
     value_returned = datetimeformat(self.context,
                                     date_today,
                                     output='json')
     assert value_expected == value_returned
Exemplo n.º 34
0
 def test_time(self):
     """Expects time format."""
     value_test = datetime.fromordinal(733900)
     value_localize = self.timezone.localize(value_test)
     value_expected = format_time(value_localize, locale=self.locale,
                                  tzinfo=self.timezone)
     value_returned = datetimeformat(self.context, value_test,
                                     format='time')
     eq_(pq(value_returned)('time').text(), value_expected)
Exemplo n.º 35
0
async def vars_parser(text,
                      message,
                      chat_id,
                      md=False,
                      event: Message = None,
                      user=None):
    if event is None:
        event = message

    if not text:
        return text

    language_code = await get_chat_lang(chat_id)
    current_datetime = datetime.now()

    first_name = html.escape(user.first_name, quote=False)
    last_name = html.escape(user.last_name or "", quote=False)
    user_id = ([user.id for user in event.new_chat_members][0]
               if "new_chat_members" in event and event.new_chat_members != []
               else user.id)
    mention = await get_user_link(user_id, md=md)

    if (hasattr(event, "new_chat_members") and event.new_chat_members
            and event.new_chat_members[0].username):
        username = "******" + event.new_chat_members[0].username
    elif user.username:
        username = "******" + user.username
    else:
        username = mention

    chat_id = message.chat.id
    chat_name = html.escape(message.chat.title or "Local", quote=False)
    chat_nick = message.chat.username or chat_name

    current_date = html.escape(format_date(date=current_datetime,
                                           locale=language_code),
                               quote=False)
    current_time = html.escape(format_time(time=current_datetime,
                                           locale=language_code),
                               quote=False)
    current_timedate = html.escape(format_datetime(datetime=current_datetime,
                                                   locale=language_code),
                                   quote=False)

    text = (text.replace("{first}", first_name).replace(
        "{last}",
        last_name).replace("{fullname}", first_name + " " + last_name).replace(
            "{id}",
            str(user_id).replace("{userid}", str(user_id))).replace(
                "{mention}", mention).replace("{username}", username).replace(
                    "{chatid}", str(chat_id)).replace(
                        "{chatname}", str(chat_name)).replace(
                            "{chatnick}", str(chat_nick)).replace(
                                "{date}", str(current_date)).replace(
                                    "{time}", str(current_time)).replace(
                                        "{timedate}", str(current_timedate)))
    return text
Exemplo n.º 36
0
def format_time(time=None, format='medium'):
    """Returns a time formated according to the given format in the context
    of current locale. If `time` is None, current time is assumed.

    :param time: an instance of :class:`~datetime.time` or None
    :param format: format pattern, one of `short`, `medium`, `long` or `full`.
    :returns: formated time as string
    """
    return dates.format_time(time, format=format, locale=get_locale())
Exemplo n.º 37
0
 def test_today(self):
     """Expects shortdatetime, format: Today at {time}."""
     date_today = datetime.today()
     date_localize = self.timezone.localize(date_today)
     value_returned = unicode(datetimeformat(self.context, date_today))
     value_expected = 'Today at %s' % format_time(date_localize,
                                                  format='short',
                                                  locale=self.locale,
                                                  tzinfo=self.timezone)
     eq_(pq(value_returned)('time').text(), value_expected)
Exemplo n.º 38
0
def format_date_value(value, tzvalue, locale, format):
    if format == "shortdatetime":
        # Check if the date is today
        if value.toordinal() == datetime.date.today().toordinal():
            formatted = dates.format_time(tzvalue, format="short", locale=locale)
            return _("Today at %s") % formatted
        else:
            return dates.format_datetime(tzvalue, format="short", locale=locale)
    elif format == "longdatetime":
        return dates.format_datetime(tzvalue, format="long", locale=locale)
    elif format == "date":
        return dates.format_date(tzvalue, locale=locale)
    elif format == "time":
        return dates.format_time(tzvalue, locale=locale)
    elif format == "datetime":
        return dates.format_datetime(tzvalue, locale=locale)
    else:
        # Unknown format
        raise DateTimeFormatError
Exemplo n.º 39
0
def date_fmt(ctx, obj, fmt='medium'):
    loc = ctx.get('i18n', None)
    if loc:
        if isinstance(obj, datetime.datetime):
            return format_datetime(obj, fmt, locale=loc)
        if isinstance(obj, datetime.time):
            return format_time(obj, fmt, locale=loc)
        if isinstance(obj, datetime.date):
            return format_date(obj, fmt, locale=loc)
    return str(obj)
Exemplo n.º 40
0
 def format_dt(self, value, format='short', parts='dt', localtime=True):
     if localtime:
         dt = self.normalize(value)
     else:
         dt = value
     if parts == 'd':
         return format_date(dt, format=format, locale=self.locale)
     if parts == 't':
         return format_time(dt, format=format, locale=self.locale)
     return format_datetime(dt, format=format, locale=self.locale)
Exemplo n.º 41
0
    def time(self, time=None, format='medium'):
        """Return a time formatted according to the given pattern.

        >>> from datetime import datetime
        >>> from pytz import timezone
        >>> fmt = Format('en_US', tzinfo=timezone('US/Eastern'))
        >>> fmt.time(datetime(2007, 4, 1, 15, 30))
        u'11:30:00 AM'
        """
        return format_time(time, format, tzinfo=self.tzinfo, locale=self.locale)
Exemplo n.º 42
0
 def test_today(self):
     """Expects shortdatetime, format: Today at {time}."""
     date_today = datetime.today()
     date_localize = self.timezone.localize(date_today)
     value_returned = unicode(datetimeformat(self.context, date_today))
     value_expected = 'Today at %s' % format_time(date_localize,
                                                  format='short',
                                                  locale=self.locale,
                                                  tzinfo=self.timezone)
     eq_(pq(value_returned)('time').text(), value_expected)
Exemplo n.º 43
0
 def format_dt(self, value, format='short', parts = 'dt', localtime = True):
     if localtime:
         dt = self.normalize(value)
     else:
         dt = value
     if parts == 'd':
         return format_date(dt, format = format, locale = self.locale)
     if parts == 't':
         return format_time(dt, format = format, locale = self.locale)
     return format_datetime(dt, format = format, locale = self.locale)
Exemplo n.º 44
0
Arquivo: utils.py Projeto: Elchi3/kuma
def format_date_value(value, tzvalue, locale, format):
    if format == "shortdatetime":
        # Check if the date is today
        if value.toordinal() == datetime.date.today().toordinal():
            formatted = dates.format_time(tzvalue, format="short", locale=locale)
            return _(u"Today at %s") % formatted
        else:
            return dates.format_datetime(tzvalue, format="short", locale=locale)
    elif format == "longdatetime":
        return dates.format_datetime(tzvalue, format="long", locale=locale)
    elif format == "date":
        return dates.format_date(tzvalue, locale=locale)
    elif format == "time":
        return dates.format_time(tzvalue, locale=locale)
    elif format == "datetime":
        return dates.format_datetime(tzvalue, locale=locale)
    else:
        # Unknown format
        raise DateTimeFormatError
Exemplo n.º 45
0
def test_no_inherit_metazone_marker_never_in_output(locale):
    # See: https://github.com/python-babel/babel/issues/428
    tz = pytz.timezone('America/Los_Angeles')
    t = tz.localize(datetime(2016, 1, 6, 7))
    assert NO_INHERITANCE_MARKER not in dates.format_time(t,
                                                          format='long',
                                                          locale=locale)
    assert NO_INHERITANCE_MARKER not in dates.get_timezone_name(t,
                                                                width='short',
                                                                locale=locale)
Exemplo n.º 46
0
 def test_hour_formatting(self):
     l = 'en_US'
     t = time(0, 0, 0)
     self.assertEqual(dates.format_time(t, 'h a', locale=l), '12 AM')
     self.assertEqual(dates.format_time(t, 'H', locale=l), '0')
     self.assertEqual(dates.format_time(t, 'k', locale=l), '24')
     self.assertEqual(dates.format_time(t, 'K a', locale=l), '0 AM')
     t = time(12, 0, 0)
     self.assertEqual(dates.format_time(t, 'h a', locale=l), '12 PM')
     self.assertEqual(dates.format_time(t, 'H', locale=l), '12')
     self.assertEqual(dates.format_time(t, 'k', locale=l), '12')
     self.assertEqual(dates.format_time(t, 'K a', locale=l), '0 PM')
Exemplo n.º 47
0
 def test_hour_formatting(self):
     l = 'en_US'
     t = time(0, 0, 0)
     self.assertEqual(dates.format_time(t, 'h a', locale=l), '12 AM')
     self.assertEqual(dates.format_time(t, 'H', locale=l), '0')
     self.assertEqual(dates.format_time(t, 'k', locale=l), '24')
     self.assertEqual(dates.format_time(t, 'K a', locale=l), '0 AM')
     t = time(12, 0, 0)
     self.assertEqual(dates.format_time(t, 'h a', locale=l), '12 PM')
     self.assertEqual(dates.format_time(t, 'H', locale=l), '12')
     self.assertEqual(dates.format_time(t, 'k', locale=l), '12')
     self.assertEqual(dates.format_time(t, 'K a', locale=l), '0 PM')
Exemplo n.º 48
0
    def to_html(self, locale_code):
        if self.data_type == 'currency':
            return '<td data-sort-order="{0:0=8X}" class="data-type-{1}"><data value="{2}">{3}</data></td>'.format(
                self.sort_order, self.data_type, self.data_value,
                format_currency(self.data_value,
                                currency=self.options['currency'],
                                locale=locale_code))
        elif self.data_type == 'date':
            return '<td data-sort-order="{0:0=8X}" class="data-type-{1}"><time datetime="{2}">{3}</time></td>'.format(
                self.sort_order, self.data_type, self.data_value.isoformat(),
                format_date(self.data_value,
                            format=self.options['format'],
                            locale=locale_code))
        elif self.data_type == 'datetime':
            return '<td data-sort-order="{0:0=8X}" class="data-type-{1}"><time datetime="{2}">{3}</time></td>'.format(
                self.sort_order, self.data_type, self.data_value.isoformat(),
                format_datetime(self.data_value,
                                format=self.options['format'],
                                locale=locale_code))
        elif self.data_type == 'decimal':
            return '<td data-sort-order="{0:0=8X}" class="data-type-{1}"><data value="{2}">{3}</data></td>'.format(
                self.sort_order, self.data_type, self.data_value,
                format_decimal(self.data_value, locale=locale_code))
        elif self.data_type == 'interval':
            return '<td data-sort-order="{0:0=8X}" class="data-type-{1}"><data value="{2}">{3}</data></td>'.format(
                self.sort_order, self.data_type, self.data_value,
                format_interval(self.data_value[0],
                                self.data_value[1],
                                locale=locale_code))
        elif self.data_type == 'percent':
            return '<td data-sort-order="{0:0=8X}" class="data-type-{1}"><data value="{2}">{3}</data></td>'.format(
                self.sort_order, self.data_type, self.data_value,
                format_percent(self.data_value, locale=locale_code))
        elif self.data_type == 'scientific':
            return '<td data-sort-order="{0:0=8X}" class="data-type-{1}"><data value="{2}">{3}</data></td>'.format(
                self.sort_order, self.data_type, self.data_value,
                format_scientific(self.data_value, locale=locale_code))
        elif self.data_type == 'time':
            return '<td data-sort-order="{0:0=8X}" class="data-type-{1}"><time datetime="{2}">{3}</time></td>'.format(
                self.sort_order, self.data_type, self.data_value.isoformat(),
                format_time(self.data_value,
                            format=self.options['format'],
                            locale=locale_code))
        elif self.data_type == 'timedelta':
            temp = int(self.data_value.total_seconds())

            return '<td data-sort-order="{0:0=8X}" class="data-type-{1}"><time datetime="PT{2}H{3}M{4}S">{5}</time></td>'.format(
                self.sort_order, self.data_type, temp % 60, (temp // 60) % 60,
                (temp // 3600),
                format_timedelta(self.data_value,
                                 format=self.options['format'],
                                 locale=locale_code))

        return '<td data-sort-order="{0:0=8X}" class="data-type-{1}">{2}</td>'.format(
            self.sort_order, self.data_type, self.content)
Exemplo n.º 49
0
    def format_time(self, time=None, format='medium', tzinfo=None):
        """
        Return a time formatted according to the locale.

        :param time: the time or datetime object; if None, the current time
                     in UTC is used
        :param format: one of "full", "long", "medium", or "short", or a
                       custom date/time pattern
        :param tzinfo: the time-zone to apply to the time for display
        """
        return dates.format_time(time, format, tzinfo, self)
Exemplo n.º 50
0
def format_element(element):
    # literal
    for value in element.get('http://www.w3.org/1999/02/22-rdf-syntax-ns#value', []):
        type = value.get('@type', '')
        val = value.get('@value', '')
        if type == 'http://www.w3.org/2001/XMLSchema#dateTime':
            bc = (val[0] == '-')
            try:
                return format_datetime(datetime.strptime(val, ('-' if bc else '') + '%Y-%m-%dT%H:%M:%SZ'),
                                       locale=locale, format='full') + (
                           ' ' + locale.eras['wide'][0] if bc else '')
            except ValueError:
                return val
        elif type == 'http://www.w3.org/2001/XMLSchema#date':
            bc = (val[0] == '-')
            try:
                return format_date(datetime.strptime(val, ('-' if bc else '') + '%Y-%m-%dZ'), locale=locale,
                                   format='full') + (' ' + locale.eras['wide'][0] if bc else '')
            except ValueError:
                return val
        elif type == 'http://www.w3.org/2001/XMLSchema#decimal' or \
                type == 'http://www.w3.org/2001/XMLSchema#double' or \
                type == 'http://www.w3.org/2001/XMLSchema#float':
            return format_decimal(float(val), locale=locale)
        elif type == 'http://www.w3.org/2001/XMLSchema#integer':
            return format_number(int(val), locale=locale)
        elif type == 'http://www.w3.org/2001/XMLSchema#time':
            try:
                return format_time(datetime.strptime(val, '%H:%M:%SZ'), locale=locale, format='full')
            except ValueError:
                return val
        else:
            return val

    # entities
    types = element.get('@type', [])

    if 'http://schema.org/GeoCoordinates' in types and \
            'http://schema.org/latitude' in element and \
            'http://schema.org/longitude' in element:
        latitude = float(element['http://schema.org/latitude'][0]['@value'])
        longitude = float(element['http://schema.org/longitude'][0]['@value'])
        lat_dir = 'north' if latitude >= 0 else 'south'
        lon_dir = 'east' if longitude >= 0 else 'west'
        return format_unit(abs(latitude), 'angle-degree', locale=locale) + ' ' + lat_dir + ' ' + \
               format_unit(abs(longitude), 'angle-degree', locale=locale) + ' ' + lon_dir
    else:
        for same_as in element.get('http://schema.org/sameAs', []):
            url = same_as.get('@id', same_as.get('@value', ''))
            if url.startswith('http://twitter.com/'):
                return url.replace('http://twitter.com/', '@')
        for name in element.get('http://schema.org/name', []):
            return name.get('@value', '')
    return ''
Exemplo n.º 51
0
 def time(self, time, format=MEDIUM):
     """
     Format time
     :param time:    The time 
     :param format:  The format 
     :return:        Formatted time
     """
     return format_time(time,
                        format=format,
                        locale=self._locale,
                        tzinfo=self.time_zone)
Exemplo n.º 52
0
def get_message_title(message, language):
    conversation = message.conversation
    author_name = message.author.display_name
    type = conversation.type()

    if message.is_thread_reply():
        thread_start = Truncator(message.thread.content).chars(num=15)
        return '{} / {}'.format(thread_start, author_name)

    if type == 'group':
        return '{} / {}'.format(conversation.target.name, author_name)

    if type == 'pickup':
        pickup = conversation.target
        group_tz = pickup.store.group.timezone
        with timezone.override(group_tz):
            weekday = format_date(
                pickup.date.astimezone(timezone.get_current_timezone()),
                'EEEE',
                locale=translation.to_locale(language),
            )
            time = format_time(
                pickup.date,
                format='short',
                locale=translation.to_locale(language),
                tzinfo=timezone.get_current_timezone(),
            )
        short_date = '{} {}'.format(weekday, time)
        short_name = _('Pickup %(date)s') % {
            'date': short_date,
        }
        return '{} / {}'.format(short_name, author_name)

    if type == 'application':
        application = conversation.target
        applicant_name = application.user.display_name
        if applicant_name == '':
            applicant_name = '(?)'

        emoji = '❓'
        if application.status == GroupApplicationStatus.ACCEPTED.value:
            emoji = '✅'
        elif application.status == GroupApplicationStatus.DECLINED.value:
            emoji = '❌'
        elif application.status == GroupApplicationStatus.WITHDRAWN.value:
            emoji = '🗑️'
        application_title = '{} {}'.format(emoji, applicant_name)

        if message.author == application.user:
            return application_title
        else:
            return '{} / {}'.format(application_title, author_name)

    return author_name
Exemplo n.º 53
0
def format_cell(cell, locale=None):
    value = cell.value
    formatted_value = value or '&nbsp;'
    number_format = cell.number_format
    if not number_format:
        return formatted_value
    if isinstance(value, six.integer_types) or isinstance(value, float):
        if number_format.lower() != 'general':
            locale = locale or LC_NUMERIC
            formatted_value = format_decimal(value,
                                             number_format,
                                             locale=locale)

    locale = locale or LC_TIME

    # Possible problem with dd-mmm and more
    number_format = FIX_BUILTIN_FORMATS.get(cell._style.numFmtId,
                                            number_format)
    number_format = number_format.split(';')[0]

    try:
        # Get local from cell
        m = re.match('\[\$[-0-9A-Fa-f][0-9A-Fa-f]{3}\]', number_format)
        if m:
            win_locale = m.group()
            new_locale = win_locale_lookup.get(win_locale.upper())
            if new_locale:
                locale = new_locale
            else:
                logger.warning(
                    'Unable to lookup win locale {}'.format(number_format))
            number_format = number_format.replace(win_locale, '')
    except:
        logger.warning('Unable to get win locale {}'.format(number_format),
                       exc_info=True)

    try:
        if type(value) == datetime.date:
            number_format = normalize_date_format(number_format)
            formatted_value = format_date(value, number_format, locale=locale)
        elif type(value) == datetime.datetime:
            number_format = normalize_datetime_format(number_format)
            formatted_value = format_datetime(value,
                                              number_format,
                                              locale=locale)
        elif type(value) == datetime.time:
            number_format = normalize_time_format(number_format)
            formatted_value = format_time(value, number_format, locale=locale)
    except:
        logger.warning('Unable to properly format cell {}'.format(cell),
                       exc_info=True)
        return str(formatted_value)
    return formatted_value
Exemplo n.º 54
0
def activity_reminder(participant_id):
    participant = ActivityParticipant.objects.filter(id=participant_id).first()
    if not participant:
        return

    activity = participant.activity
    user = participant.user
    language = user.language
    tz = activity.group.timezone

    with translation.override(language), timezone.override(tz):
        if is_past(activity.date.start):
            return

        subscriptions = PushSubscription.objects.filter(user=user)
        if subscriptions.count() == 0:
            return

        emoji = '⏰'

        if is_today(activity.date.start):
            when = format_time(
                activity.date.start,
                format='short',
                locale=translation.to_locale(language),
                tzinfo=tz,
            )
        else:
            when = format_datetime(
                activity.date.start,
                format='medium',  # short gives US date format in English, is confusing!
                locale=translation.to_locale(language),
                tzinfo=tz,
            )

        where = ', '.join(part for part in [activity.place.name, activity.place.address] if part)

        title = _('Upcoming %(activity_type)s') % {'activity_type': activity.activity_type.get_translated_name()}
        title = f'{emoji} {title}!'

        body = Truncator(' / '.join(part for part in [when, where, activity.description] if part)).chars(num=1000)

        click_action = frontend_urls.activity_detail_url(activity)

        notify_subscribers_by_device(
            subscriptions,
            click_action=click_action,
            fcm_options={
                'message_title': title,
                'message_body': body,
                'tag': 'activity:{}'.format(activity.id),
            }
        )
Exemplo n.º 55
0
def format_date_value(value, tzvalue, locale, format):
    if format == 'shortdatetime':
        # Check if the date is today
        if value.toordinal() == datetime.date.today().toordinal():
            formatted = dates.format_time(tzvalue, format='short',
                                          locale=locale)
            return _(u'Today at %s') % formatted
        else:
            return dates.format_datetime(tzvalue, format='short',
                                         locale=locale)
    elif format == 'longdatetime':
        return dates.format_datetime(tzvalue, format='long', locale=locale)
    elif format == 'date':
        return dates.format_date(tzvalue, locale=locale)
    elif format == 'time':
        return dates.format_time(tzvalue, locale=locale)
    elif format == 'datetime':
        return dates.format_datetime(tzvalue, locale=locale)
    else:
        # Unknown format
        raise DateTimeFormatError
Exemplo n.º 56
0
def localize_time(obj, locale, format=None, **kwargs):
    """add???
    
    :param obj: add???
    :param locale: add???
    :param format: add???. Default value is ``None``
    :returns: add???
    """
    format = format or 'short'
    dt = datetime.datetime(1970, 1, 1, obj.hour, obj.minute, obj.second,
                           obj.microsecond, obj.tzinfo)
    return dates.format_time(obj, format=format, locale=locale)
Exemplo n.º 57
0
def time_filter(value, format='short', locale=None, usertz=True):  # NOQA: A002
    # Default format = hh:mm
    if isinstance(value, datetime) and usertz:
        if value.tzinfo is None:
            dt = UTC.localize(value).astimezone(get_timezone())
        else:
            dt = value.astimezone(get_timezone())
    else:
        dt = value
    return format_time(dt,
                       format=format,
                       locale=locale if locale else get_locale())  # NOQA: A002
Exemplo n.º 58
0
def index():

    d = date(1984, 8, 12)
    t = time(22, 16)


    us_num = numbers.format_decimal(1.2345, locale='en_US')
    us_cur = numbers.format_currency(1.2345, locale='en_US', currency='USD')
    us_date = dates.format_date(d, locale='en_US')
    us_time = dates.format_time(t, locale='en_US')

    se_num = numbers.format_decimal(1.2345, locale='se_SE')
    se_cur = numbers.format_currency(1.2345, locale='se_SE', currency='EUR')
    se_date = dates.format_date(d, locale='se_SE')
    se_time = dates.format_time(t, locale='se_SE')

    mt_num = numbers.format_decimal(1.2345, locale='mt_MT')
    mt_cur = numbers.format_currency(1.2345, locale='mt_MT', currency='EUR')
    mt_date = dates.format_date(d,  locale='mt_MT')
    mt_time = dates.format_time(t, locale='mt_MT')

    
    
    results = {
        'us_num':us_num, 
        'us_cur':us_cur,
        'us_date':us_date,
        'us_time':us_time,
        'se_num':se_num,
        'se_cur':se_cur,
        'se_date':se_date,
        'se_time':se_time,
        'mt_num':mt_num,
        'mt_cur':mt_cur,
        'mt_date':mt_date,
        'mt_time':mt_time,
    }
        

    return render_template('index.html', results=results)