Ejemplo n.º 1
0
def datetime_fmt_tpl(ctx, fmt='medium'):
    loc = ctx.get('i18n', None)
    if loc:
        return get_datetime_format(fmt, loc).format(
            get_time_format(fmt, loc).pattern,
            get_date_format(fmt, loc).pattern)
    return get_datetime_format(fmt).format(
        get_time_format(fmt).pattern,
        get_date_format(fmt).pattern)
Ejemplo n.º 2
0
def datetime_fmt_tpl(ctx, fmt='medium'):
	loc = ctx.get('i18n', None)
	if loc:
		return get_datetime_format(fmt, loc).format(
			get_time_format(fmt, loc).pattern,
			get_date_format(fmt, loc).pattern
		)
	return get_datetime_format(fmt).format(
		get_time_format(fmt).pattern,
		get_date_format(fmt).pattern
	)
Ejemplo n.º 3
0
def parse_to_string(date):
    """Formats the date according to the current locale and the existence of the year."""
    date_format = get_date_format(format='long',
                                  locale=get_current_locale()).pattern
    if not has_year(date):
        date_format = date_format.replace('y', '').replace(',', '').rstrip()
    return format_date(date, format=date_format, locale=get_current_locale())
Ejemplo n.º 4
0
 def get_date_format(self):
     pattern = dates.get_date_format(format=self.format, locale=settings.get_locale()).pattern
     for c in ('M', 'd', 'yy'):
         double_char = c * 2
         if double_char not in pattern:
             pattern = pattern.replace(c, double_char)
     return pattern
Ejemplo n.º 5
0
def get_datetime_format(kind="datetime"):
    """Get local datetime format.

    @param kind: type (date, time or datetime)
    @return: string

    @todo: cache formats to improve performance.
    """
    if 'lang' in cherrypy.session:
        # server-defined formatting
        if kind == 'time':
            return cherrypy.session['lang']['time_format']
        elif kind == 'date':
            return cherrypy.session['lang']['date_format']
        else:
            return "%(date_format)s %(time_format)s" % cherrypy.session['lang']

    # TODO: correctly convert from LDML to POSIX datetime formatting
    # current converter is trivial and lame and probably very easy to break
    date_format = _to_posix_format(
        dates.get_date_format(format='short', locale=get_locale())).format
    if kind == 'time':
        # Should use dates.get_time_format(locale=get_locale())
        return '%H:%M:%S'
    elif kind == 'date':
        return date_format
    else:
        # Should use dates.get_datetime_format, but that one returns
        # a 2.6-style formats
        return "%s %s" % (date_format, '%H:%M:%S')
Ejemplo n.º 6
0
def _i18n_parse_date_pattern(locale):
    format_keys = {
        'y': ('y', 'Y'),
        'M': ('M',),
        'd': ('d',),
        'h': ('h', 'H'),
        'm': ('m',),
        's': ('s',),
    }
    regexp = [r'[0-9]+']

    date_format = get_date_format('medium', locale=locale)
    time_format = get_time_format('medium', locale=locale)
    datetime_format = get_datetime_format('medium', locale=locale)
    formats = (
        datetime_format.replace('{0}', time_format.format) \
                       .replace('{1}', date_format.format),
        date_format.format)

    orders = []
    for format in formats:
        order = []
        for key, chars in format_keys.iteritems():
            for char in chars:
                idx = format.find('%(' + char)
                if idx != -1:
                    order.append((idx, key))
                    break
        order.sort()
        order = dict((key, idx) for idx, (_, key) in enumerate(order))
        orders.append(order)

    month_names = {
        'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6,
        'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12,
    }
    if formats[0].find('%(MMM)s') != -1:
        for width in ('wide', 'abbreviated'):
            names = get_month_names(width, locale=locale)
            for num, name in names.iteritems():
                name = name.lower()
                month_names[name] = num
    regexp.extend(month_names.iterkeys())

    period_names = {'am': 'am', 'pm': 'pm'}
    if formats[0].find('%(a)s') != -1:
        names = get_period_names(locale=locale)
        for period, name in names.iteritems():
            if period in ('am', 'pm'):
                name = name.lower()
                period_names[name] = period
    regexp.extend(period_names.iterkeys())

    return {
        'orders': orders,
        'regexp': re.compile('(%s)' % '|'.join(regexp),
                             re.IGNORECASE | re.UNICODE),
        'month_names': month_names,
        'period_names': period_names,
    }
Ejemplo n.º 7
0
def get_datetime_format(kind="datetime"):
    """Get local datetime format.

    @param kind: type (date, time or datetime)
    @return: string

    @todo: cache formats to improve performance.
    """
    if 'lang' in cherrypy.session:
        # server-defined formatting
        if kind == 'time':
            return cherrypy.session['lang']['time_format']
        elif kind == 'date':
            return cherrypy.session['lang']['date_format']
        else:
            return "%(date_format)s %(time_format)s"% cherrypy.session['lang']

    # TODO: correctly convert from LDML to POSIX datetime formatting
    # current converter is trivial and lame and probably very easy to break
    date_format = _to_posix_format(dates.get_date_format(
            format='short', locale=get_locale())).format
    if kind == 'time':
        # Should use dates.get_time_format(locale=get_locale())
        return '%H:%M:%S'
    elif kind == 'date':
        return date_format
    else:
        # Should use dates.get_datetime_format, but that one returns
        # a 2.6-style formats
        return "%s %s" % (date_format, '%H:%M:%S')
Ejemplo n.º 8
0
def _i18n_parse_date_pattern(locale):
    format_keys = {
        'y': ('y', 'Y'),
        'M': ('M',),
        'd': ('d',),
        'h': ('h', 'H'),
        'm': ('m',),
        's': ('s',),
    }
    regexp = [r'[0-9]+']

    date_format = get_date_format('medium', locale=locale)
    time_format = get_time_format('medium', locale=locale)
    datetime_format = get_datetime_format('medium', locale=locale)
    formats = (
        datetime_format.replace('{0}', time_format.format) \
                       .replace('{1}', date_format.format),
        date_format.format)

    orders = []
    for format in formats:
        order = []
        for key, chars in format_keys.iteritems():
            for char in chars:
                idx = format.find('%(' + char)
                if idx != -1:
                    order.append((idx, key))
                    break
        order.sort()
        order = dict((key, idx) for idx, (_, key) in enumerate(order))
        orders.append(order)

    month_names = {
        'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6,
        'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12,
    }
    if formats[0].find('%(MMM)s') != -1:
        for width in ('wide', 'abbreviated'):
            names = get_month_names(width, locale=locale)
            for num, name in names.iteritems():
                name = name.lower()
                month_names[name] = num
    regexp.extend(month_names.iterkeys())

    period_names = {'am': 'am', 'pm': 'pm'}
    if formats[0].find('%(a)s') != -1:
        names = get_period_names(locale=locale)
        for period, name in names.iteritems():
            name = name.lower()
            period_names[name] = period
    regexp.extend(period_names.iterkeys())

    return {
        'orders': orders,
        'regexp': re.compile('(%s)' % '|'.join(regexp),
                             re.IGNORECASE | re.UNICODE),
        'month_names': month_names,
        'period_names': period_names,
    }
Ejemplo n.º 9
0
    def get_date_format(self, format='medium'):
        """Return the date formatting pattern for the specified format

        In:
          - ``format`` -- 'full', 'long', 'medium' or 'short'

        Return:
          - the date formatting pattern
        """
        return dates.get_date_format(format, self)
Ejemplo n.º 10
0
def get_date_format_hint(locale=None):
    """Present the default format used by `format_date` in a human readable
    form.
    This is a format that will be recognized by `parse_date` when reading a
    date.
    """
    if locale == 'iso8601':
        return 'YYYY-MM-DD'
    if babel and locale:
        format = get_date_format('medium', locale=locale)
        return format.pattern
    return _libc_get_date_format_hint()
Ejemplo n.º 11
0
def get_date_format_hint(locale=None):
    """Present the default format used by `format_date` in a human readable
    form.
    This is a format that will be recognized by `parse_date` when reading a
    date.
    """
    if locale == 'iso8601':
        return 'YYYY-MM-DD'
    if babel and locale:
        format = get_date_format('medium', locale=locale)
        return format.pattern
    return _libc_get_date_format_hint()
Ejemplo n.º 12
0
def get_date_format_jquery_ui(locale):
    """Get the date format for the jQuery UI datepicker library."""
    if locale == 'iso8601':
        return 'yy-mm-dd'
    if babel and locale:
        values = {'yyyy': 'yy', 'y': 'yy', 'M': 'm', 'MM': 'mm', 'MMM': 'M',
                  'd': 'd', 'dd': 'dd'}
        return get_date_format('medium', locale=locale).format % values

    t = datetime(1999, 10, 29, tzinfo=utc)
    tmpl = format_date(t, tzinfo=utc)
    return tmpl.replace('1999', 'yy', 1).replace('99', 'y', 1) \
               .replace('10', 'mm', 1).replace('29', 'dd', 1)
Ejemplo n.º 13
0
def get_date_format_jquery_ui(locale):
    """Get the date format for the jQuery UI datepicker library."""
    if locale == 'iso8601':
        return 'yy-mm-dd'
    if babel and locale:
        values = {'yyyy': 'yy', 'y': 'yy', 'M': 'm', 'MM': 'mm', 'MMM': 'M',
                  'd': 'd', 'dd': 'dd'}
        return get_date_format('medium', locale=locale).format % values

    t = datetime(1999, 10, 29, tzinfo=utc)
    tmpl = format_date(t, tzinfo=utc)
    return tmpl.replace('1999', 'yy', 1).replace('99', 'y', 1) \
               .replace('10', 'mm', 1).replace('29', 'dd', 1)
Ejemplo n.º 14
0
    def get_date_format(self, format='medium'):
        """Return the date formatting pattern for the specified format

        >>> Locale('en', 'US').get_date_format()
        <DateTimePattern u'MMM d, yyyy'>
        >>> Locale('de', 'DE').get_date_format('full')
        <DateTimePattern u'EEEE, d. MMMM yyyy'>

        In:
          - ``format`` -- 'full', 'long', 'medium' or 'short'

        Return:
          - the date formatting pattern
        """
        return dates.get_date_format(format, self)
Ejemplo n.º 15
0
def get_datetime_format_hint(locale=None):
    """Present the default format used by `format_datetime` in a human readable
    form.
    This is a format that will be recognized by `parse_date` when reading a
    date.
    """
    if locale == 'iso8601':
        return u'YYYY-MM-DDThh:mm:ss±hh:mm'
    if babel and locale:
        date_pattern = get_date_format('medium', locale=locale).pattern
        time_pattern = get_time_format('medium', locale=locale).pattern
        format = get_datetime_format('medium', locale=locale)
        return format.replace('{0}', time_pattern) \
                     .replace('{1}', date_pattern)
    return _libc_get_datetime_format_hint()
Ejemplo n.º 16
0
def get_datetime_format_hint(locale=None):
    """Present the default format used by `format_datetime` in a human readable
    form.
    This is a format that will be recognized by `parse_date` when reading a
    date.
    """
    if locale == 'iso8601':
        return u'YYYY-MM-DDThh:mm:ss±hh:mm'
    if babel and locale:
        date_pattern = get_date_format('medium', locale=locale).pattern
        time_pattern = get_time_format('medium', locale=locale).pattern
        format = get_datetime_format('medium', locale=locale)
        return format.replace('{0}', time_pattern) \
                     .replace('{1}', date_pattern)
    return _libc_get_datetime_format_hint()
Ejemplo n.º 17
0
def get_date_format_hint(locale=None):
    """Present the default format used by `format_date` in a human readable
    form.
    This is a format that will be recognized by `parse_date` when reading a
    date.
    """
    if locale == 'iso8601':
        return 'YYYY-MM-DD'
    if babel and locale:
        format = get_date_format('medium', locale=locale)
        return format.pattern

    t = datetime(1999, 10, 29, tzinfo=utc)
    tmpl = format_date(t, tzinfo=utc)
    return tmpl.replace('1999', 'YYYY', 1).replace('99', 'YY', 1) \
               .replace('10', 'MM', 1).replace('29', 'DD', 1)
Ejemplo n.º 18
0
def get_date_format_hint(locale=None):
    """Present the default format used by `format_date` in a human readable
    form.
    This is a format that will be recognized by `parse_date` when reading a
    date.
    """
    if locale == 'iso8601':
        return 'YYYY-MM-DD'
    if babel and locale:
        format = get_date_format('medium', locale=locale)
        return format.pattern

    t = datetime(1999, 10, 29, tzinfo=utc)
    tmpl = format_date(t, tzinfo=utc)
    return tmpl.replace('1999', 'YYYY', 1).replace('99', 'YY', 1) \
               .replace('10', 'MM', 1).replace('29', 'DD', 1)
Ejemplo n.º 19
0
def get_datetime_format(kind="datetime"):
    """Get local datetime format.

    @param kind: type (date, time or datetime)
    @return: string

    @todo: cache formats to improve performance.
    @todo: extend user preferences to allow customisable date format (tiny server).
    """

    fmt = "%H:%M:%S"

    if kind != "time":
        fmt =  dates.get_date_format("short", locale=get_locale()).format
        fmt = _to_posix_format(fmt)

    if kind == "datetime":
        fmt += " %H:%M:%S"

    return fmt
Ejemplo n.º 20
0
def get_datetime_format(kind="datetime"):
    """Get local datetime format.

    @param kind: type (date, time or datetime)
    @return: string

    @todo: cache formats to improve performance.
    @todo: extend user preferences to allow customisable date format (tiny server).
    """

    fmt = "%H:%M:%S"

    if kind != "time":
        fmt = dates.get_date_format("short", locale=get_locale()).format
        fmt = _to_posix_format(fmt)

    if kind == "datetime":
        fmt += " %H:%M:%S"

    return fmt
Ejemplo n.º 21
0
def get_datetime_format_hint(locale=None):
    """Present the default format used by `format_datetime` in a human readable
    form.
    This is a format that will be recognized by `parse_date` when reading a
    date.
    """
    if locale == 'iso8601':
        return u'YYYY-MM-DDThh:mm:ss±hh:mm'
    if babel and locale:
        date_pattern = get_date_format('medium', locale=locale).pattern
        time_pattern = get_time_format('medium', locale=locale).pattern
        format = get_datetime_format('medium', locale=locale)
        return format.replace('{0}', time_pattern) \
                     .replace('{1}', date_pattern)

    t = datetime(1999, 10, 29, 23, 59, 58, tzinfo=utc)
    tmpl = format_datetime(t, tzinfo=utc)
    return tmpl.replace('1999', 'YYYY', 1).replace('99', 'YY', 1) \
               .replace('10', 'MM', 1).replace('29', 'DD', 1) \
               .replace('23', 'hh', 1).replace('11', 'hh', 1) \
               .replace('59', 'mm', 1).replace('58', 'ss', 1)
Ejemplo n.º 22
0
def get_datetime_format_hint(locale=None):
    """Present the default format used by `format_datetime` in a human readable
    form.
    This is a format that will be recognized by `parse_date` when reading a
    date.
    """
    if locale == 'iso8601':
        return u'YYYY-MM-DDThh:mm:ss±hh:mm'
    if babel and locale:
        date_pattern = get_date_format('medium', locale=locale).pattern
        time_pattern = get_time_format('medium', locale=locale).pattern
        format = get_datetime_format('medium', locale=locale)
        return format.replace('{0}', time_pattern) \
                     .replace('{1}', date_pattern)

    t = datetime(1999, 10, 29, 23, 59, 58, tzinfo=utc)
    tmpl = format_datetime(t, tzinfo=utc)
    return tmpl.replace('1999', 'YYYY', 1).replace('99', 'YY', 1) \
               .replace('10', 'MM', 1).replace('29', 'DD', 1) \
               .replace('23', 'hh', 1).replace('11', 'hh', 1) \
               .replace('59', 'mm', 1).replace('58', 'ss', 1)
Ejemplo n.º 23
0
def parselocal_date(txt, locale):
    """TODO

    :param txt: TODO
    :param locale: the current locale (e.g: en, en_us, it)
    """
    if txt.isdigit() and len(txt) in (6, 8):  # is a date without separators: 101207
        result = {}
        format = dates.get_date_format(locale=locale).pattern.lower()
        year_idx = format.index('y')
        month_idx = format.index('m')
        if month_idx < 0:
            month_idx = format.index('l')
        day_idx = format.index('d')
        indexes = [(year_idx, 'Y'), (month_idx, 'M'), (day_idx, 'D')]
        indexes.sort()
        is8 = (len(txt) == 8)
        for i, k in indexes:
            w = 2
            if k == 'Y':
                if is8:
                    w = 4
                    result[k] = int(txt[:w])
                else:
                    year = int(txt[:w])
                    if year < 70:
                        result[k] = 2000 + year
                    else:
                        result[k] = 1900 + year
            else:
                result[k] = int(txt[:w])
            txt = txt[w:]
        return datetime.date(result['Y'], result['M'], result['D'])
    else:
        try:
            date = dates.parse_date(txt, locale)
        except:
            raise GnrException('Invalid date')
        return date
Ejemplo n.º 24
0
def parselocal_date(txt, locale):
    """TODO
    
    :param txt: TODO
    :param locale: the current locale (e.g: en, en_us, it)"""
    if txt.isdigit() and len(txt) in (6, 8): # is a date without separators: 101207
        result = {}
        format = dates.get_date_format(locale=locale).pattern.lower()
        year_idx = format.index('y')
        month_idx = format.index('m')
        if month_idx < 0:
            month_idx = format.index('l')
        day_idx = format.index('d')
        indexes = [(year_idx, 'Y'), (month_idx, 'M'), (day_idx, 'D')]
        indexes.sort()
        is8 = (len(txt) == 8)
        for i, k in indexes:
            w = 2
            if k == 'Y':
                if is8:
                    w = 4
                    result[k] = int(txt[:w])
                else:
                    year = int(txt[:w])
                    if year < 70:
                        result[k] = 2000 + year
                    else:
                        result[k] = 1900 + year
            else:
                result[k] = int(txt[:w])
            txt = txt[w:]
        return datetime.date(result['Y'], result['M'], result['D'])
    else:
        try:
            date = dates.parse_date(txt, locale)
        except:
            raise GnrException('Invalid date')
        return date
Ejemplo n.º 25
0
def parselocal_date(txt, locale):
    """add???
    
    :param txt: add???
    :param locale: add???
    :returns: add???
    """
    if txt.isdigit() and len(txt) in (
            6, 8):  # is a date without separators: 101207
        result = {}
        format = dates.get_date_format(locale=locale).pattern.lower()
        year_idx = format.index('y')
        month_idx = format.index('m')
        if month_idx < 0:
            month_idx = format.index('l')
        day_idx = format.index('d')
        indexes = [(year_idx, 'Y'), (month_idx, 'M'), (day_idx, 'D')]
        indexes.sort()
        is8 = (len(txt) == 8)
        for i, k in indexes:
            w = 2
            if k == 'Y':
                if is8:
                    w = 4
                    result[k] = int(txt[:w])
                else:
                    year = int(txt[:w])
                    if year < 70:
                        result[k] = 2000 + year
                    else:
                        result[k] = 1900 + year
            else:
                result[k] = int(txt[:w])
            txt = txt[w:]
        return datetime.date(result['Y'], result['M'], result['D'])
    else:
        return dates.parse_date(txt, locale)
Ejemplo n.º 26
0
def parselocal_date(txt, locale):
    """add???
    
    :param txt: add???
    :param locale: add???
    :returns: add???
    """
    if txt.isdigit() and len(txt) in (6, 8): # is a date without separators: 101207
        result = {}
        format = dates.get_date_format(locale=locale).pattern.lower()
        year_idx = format.index('y')
        month_idx = format.index('m')
        if month_idx < 0:
            month_idx = format.index('l')
        day_idx = format.index('d')
        indexes = [(year_idx, 'Y'), (month_idx, 'M'), (day_idx, 'D')]
        indexes.sort()
        is8 = (len(txt) == 8)
        for i, k in indexes:
            w = 2
            if k == 'Y':
                if is8:
                    w = 4
                    result[k] = int(txt[:w])
                else:
                    year = int(txt[:w])
                    if year < 70:
                        result[k] = 2000 + year
                    else:
                        result[k] = 1900 + year
            else:
                result[k] = int(txt[:w])
            txt = txt[w:]
        return datetime.date(result['Y'], result['M'], result['D'])
    else:
        return dates.parse_date(txt, locale)
Ejemplo n.º 27
0
 def datetime_format(format='medium', locale=LC_TIME):
     time_format = unicode(get_time_format(format, locale))
     date_format = unicode(get_date_format(format, locale))
     return convert_LDML_to_MySQL( get_datetime_format(format, locale)\
             .replace('{0}', time_format)\
             .replace('{1}', date_format) )
Ejemplo n.º 28
0
--- tracwatchlist/util.py.orig	2013-08-15 04:15:56.000000000 +0800
+++ tracwatchlist/util.py	2013-08-15 04:16:05.000000000 +0800
@@ -198,8 +198,8 @@
 try:
     from  babel.dates        import  get_datetime_format, get_date_format, get_time_format
     def datetime_format(format='medium', locale=LC_TIME):
-        time_format = unicode(get_time_format(format, locale))
-        date_format = unicode(get_date_format(format, locale))
+        time_format = unicode(get_time_format(format, locale=locale))
+        date_format = unicode(get_date_format(format, locale=locale))
         return convert_LDML_to_MySQL( get_datetime_format(format, locale)\
                 .replace('{0}', time_format)\
                 .replace('{1}', date_format) )
Ejemplo n.º 29
0
def _i18n_parse_date_pattern(locale):
    format_keys = {
        'y': ('y', 'Y'),
        'M': ('M',),
        'd': ('d',),
        'h': ('h', 'H'),
        'm': ('m',),
        's': ('s',),
    }

    if locale is None:
        formats = (_libc_get_datetime_format_hint(format=True),
                   _libc_get_date_format_hint(format=True))
    else:
        date_format = get_date_format('medium', locale=locale)
        time_format = get_time_format('medium', locale=locale)
        datetime_format = get_datetime_format('medium', locale=locale)
        formats = (datetime_format.replace('{0}', time_format.format) \
                                  .replace('{1}', date_format.format),
                   date_format.format)

    orders = []
    for format in formats:
        order = []
        for key, chars in format_keys.iteritems():
            for char in chars:
                idx = format.find('%(' + char)
                if idx != -1:
                    order.append((idx, key))
                    break
        order.sort()
        orders.append(dict((key, idx) for idx, (_, key) in enumerate(order)))

    # always allow using English names regardless of locale
    month_names = dict(zip(('jan', 'feb', 'mar', 'apr', 'may', 'jun',
                            'jul', 'aug', 'sep', 'oct', 'nov', 'dec',),
                           xrange(1, 13)))
    period_names = {'am': 'am', 'pm': 'pm'}

    if locale is None:
        for num in xrange(1, 13):
            t = datetime(1999, num, 1, tzinfo=utc)
            names = format_date(t, '%b\t%B', utc).split('\t')
            month_names.update((name.lower(), num) for name in names
                               if str(num) not in name)
        for num, period in ((11, 'am'), (23, 'pm')):
            t = datetime(1999, 1, 1, num, tzinfo=utc)
            name = format_datetime(t, '%p', utc)
            if name:
                period_names[name.lower()] = period
    else:
        if formats[0].find('%(MMM)s') != -1:
            for width in ('wide', 'abbreviated'):
                names = get_month_names(width, locale=locale)
                month_names.update((name.lower(), num)
                                   for num, name in names.iteritems())
        if formats[0].find('%(a)s') != -1:
            names = get_period_names(locale=locale)
            period_names.update((name.lower(), period)
                                for period, name in names.iteritems()
                                if period in ('am', 'pm'))

    regexp = ['[0-9]+']
    regexp.extend(re.escape(name) for name in month_names)
    regexp.extend(re.escape(name) for name in period_names)

    return {
        'orders': orders,
        'regexp': re.compile('(%s)' % '|'.join(regexp), re.IGNORECASE),
        'month_names': month_names,
        'period_names': period_names,
    }
Ejemplo n.º 30
0
def test_get_date_format():
    us = dates.get_date_format(locale='en_US')
    assert us.pattern == u'MMM d, y'
    de = dates.get_date_format('full', locale='de_DE')
    assert de.pattern == u'EEEE, d. MMMM y'
Ejemplo n.º 31
0
 def __init__(self, format="medium", *args, **kwargs):
     super(DateField, self).__init__(*args, **kwargs)
     locale=get_current_language()
     self.format = self.widget.format = format
     self.date_format = get_date_format(locale=locale)
     self.date_example = format_date(datetime.datetime.now(), locale=locale)
Ejemplo n.º 32
0
def _i18n_parse_date_pattern(locale):
    format_keys = {
        'y': ('y', 'Y'),
        'M': ('M', ),
        'd': ('d', ),
        'h': ('h', 'H'),
        'm': ('m', ),
        's': ('s', ),
    }

    if locale is None:
        formats = (_libc_get_datetime_format_hint(format=True),
                   _libc_get_date_format_hint(format=True))
    else:
        date_format = get_date_format('medium', locale=locale)
        time_format = get_time_format('medium', locale=locale)
        datetime_format = get_datetime_format('medium', locale=locale)
        formats = (datetime_format.replace('{0}', time_format.format).replace(
            '{1}', date_format.format), date_format.format)

    orders = []
    for format in formats:
        order = []
        for key, chars in format_keys.iteritems():
            for char in chars:
                idx = format.find('%(' + char)
                if idx != -1:
                    order.append((idx, key))
                    break
        order.sort()
        orders.append({key: idx for idx, (_, key) in enumerate(order)})

    # always allow using English names regardless of locale
    month_names = dict(
        zip((
            'jan',
            'feb',
            'mar',
            'apr',
            'may',
            'jun',
            'jul',
            'aug',
            'sep',
            'oct',
            'nov',
            'dec',
        ), xrange(1, 13)))
    period_names = {'am': 'am', 'pm': 'pm'}

    if locale is None:
        for num in xrange(1, 13):
            t = datetime(1999, num, 1, tzinfo=utc)
            names = format_date(t, '%b\t%B', utc).split('\t')
            month_names.update(
                (name.lower(), num) for name in names if str(num) not in name)
        for num, period in ((11, 'am'), (23, 'pm')):
            t = datetime(1999, 1, 1, num, tzinfo=utc)
            name = format_datetime(t, '%p', utc)
            if name:
                period_names[name.lower()] = period
    else:
        if formats[0].find('%(MMM)s') != -1:
            for width in ('wide', 'abbreviated'):
                names = get_month_names(width, locale=locale)
                month_names.update(
                    (name.lower(), num) for num, name in names.iteritems())
        if formats[0].find('%(a)s') != -1:
            names = get_period_names(locale=locale)
            period_names.update((name.lower(), period)
                                for period, name in names.iteritems()
                                if period in ('am', 'pm'))

    regexp = ['[0-9]+']
    regexp.extend(re.escape(name) for name in month_names)
    regexp.extend(re.escape(name) for name in period_names)

    return {
        'orders': orders,
        'regexp': re.compile('(%s)' % '|'.join(regexp), re.IGNORECASE),
        'month_names': month_names,
        'period_names': period_names,
    }
Ejemplo n.º 33
0
 def dformat(x):
     form = get_date_format(x, lang)
     form = form.pattern.replace('y', '').replace('Y', '')
     return str(format_date(d, locale=lang,
                            format=form)).lower()
Ejemplo n.º 34
0
def test_get_date_format():
    us = dates.get_date_format(locale='en_US')
    assert us.pattern == u'MMM d, y'
    de = dates.get_date_format('full', locale='de_DE')
    assert de.pattern == u'EEEE, d. MMMM y'
     def datetime_format(format='medium', locale=LC_TIME):
-        time_format = unicode(get_time_format(format, locale))
-        date_format = unicode(get_date_format(format, locale))
+        time_format = unicode(get_time_format(format, locale=locale))
+        date_format = unicode(get_date_format(format, locale=locale))
Ejemplo n.º 36
0
 def datetime_format(format='medium', locale=LC_TIME):
     time_format = unicode(get_time_format(format, locale))
     date_format = unicode(get_date_format(format, locale))
     return convert_LDML_to_MySQL( get_datetime_format(format, locale)\
             .replace('{0}', time_format)\
             .replace('{1}', date_format) )
Ejemplo n.º 37
0
 def to_datetime(date):
     date_format = get_date_format("short", CONFIG.get("General",
                                                       "locale")).pattern
     dayfirst = date_format.startswith("d")
     yearfirst = date_format.startswith("y")
     return parse(date, dayfirst=dayfirst, yearfirst=yearfirst)