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 )
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, }
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()
def get_time_format(self, format='medium'): """Return the time formatting pattern for the specified format >>> Locale('en', 'US').get_time_format() <DateTimePattern u'h:mm:ss a'> >>> Locale('de', 'DE').get_time_format('full') <DateTimePattern u'HH:mm:ss v'> In: - ``format`` -- 'full', 'long', 'medium' or 'short' Return: - the time formatting pattern """ return dates.get_time_format(format, self)
def get_time_format_jquery_ui(locale): """Get the time format for the jQuery UI timepicker addon.""" if locale == 'iso8601': return 'hh:mm:ssz' # XXX timepicker doesn't support 'ISO_8601' if babel and locale: values = {'h': 'h', 'hh': 'hh', 'H': 'h', 'HH': 'hh', 'm': 'm', 'mm': 'mm', 's': 's', 'ss': 'ss', 'a': 'TT'} return get_time_format('medium', locale=locale).format % values t = datetime(1999, 10, 29, 23, 59, 58, tzinfo=utc) tmpl = format_time(t, tzinfo=utc) ampm = format_time(t, '%p', tzinfo=utc) if ampm: tmpl = tmpl.replace(ampm, 'TT', 1) return tmpl.replace('23', 'hh', 1).replace('11', 'hh', 1) \ .replace('59', 'mm', 1).replace('58', 'ss', 1)
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)
def get_time_format_jquery_ui(locale): """Get the time format for the jQuery UI timepicker addon.""" if locale == 'iso8601': return 'HH:mm:ssZ' if babel and locale: values = {'h': 'h', 'hh': 'hh', 'H': 'H', 'HH': 'HH', 'm': 'm', 'mm': 'mm', 's': 's', 'ss': 'ss'} f = get_time_format('medium', locale=locale).format if '%(a)s' in f: t = datetime(1999, 10, 29, 23, 59, 58, tzinfo=utc) ampm = babel_format_datetime(t, 'a', None, locale) values['a'] = 'TT' if ampm[0].isupper() else 'tt' return f % values t = datetime(1999, 10, 29, 23, 59, 58, tzinfo=utc) tmpl = format_time(t, tzinfo=utc) ampm = format_time(t, '%p', tzinfo=utc) if ampm: tmpl = tmpl.replace(ampm, 'TT' if ampm[0].isupper() else 'tt', 1) return tmpl.replace('23', 'HH', 1).replace('11', 'hh', 1) \ .replace('59', 'mm', 1).replace('58', 'ss', 1)
def get_time_format_jquery_ui(locale): """Get the time format for the jQuery UI timepicker addon.""" if locale == 'iso8601': return 'HH:mm:ssz' # XXX timepicker doesn't support 'ISO_8601' if babel and locale: values = {'h': 'h', 'hh': 'hh', 'H': 'H', 'HH': 'HH', 'm': 'm', 'mm': 'mm', 's': 's', 'ss': 'ss'} f = get_time_format('medium', locale=locale).format if '%(a)s' in f: t = datetime(1999, 10, 29, 23, 59, 58, tzinfo=utc) ampm = babel_format_datetime(t, 'a', None, locale) values['a'] = 'TT' if ampm[0].isupper() else 'tt' return f % values t = datetime(1999, 10, 29, 23, 59, 58, tzinfo=utc) tmpl = format_time(t, tzinfo=utc) ampm = format_time(t, '%p', tzinfo=utc) if ampm: tmpl = tmpl.replace(ampm, 'TT' if ampm[0].isupper() else 'tt', 1) return tmpl.replace('23', 'HH', 1).replace('11', 'hh', 1) \ .replace('59', 'mm', 1).replace('58', 'ss', 1)
def test_get_time_format(): assert dates.get_time_format(locale='en_US').pattern == u'h:mm:ss a' assert (dates.get_time_format('full', locale='de_DE').pattern == u'HH:mm:ss zzzz')
def __init__(self, format="medium", *args, **kwargs): super(TimeField, self).__init__(*args, **kwargs) locale=get_current_language() self.format = self.widget.format = format self.time_format = get_time_format(locale=locale) self.time_example = format_time(datetime.datetime.now(), locale=locale)
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, }
def _i18n_parse_date_patterns(): if not babel: return {} format_keys = { 'y': ('y', 'Y'), 'M': ('M', ), 'd': ('d', ), 'h': ('h', 'H'), 'm': ('m', ), 's': ('s', ), } patterns = {} for locale in get_available_locales(): 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()) patterns[locale] = { 'orders': orders, 'regexp': re.compile('(%s)' % '|'.join(regexp), re.IGNORECASE | re.UNICODE), 'month_names': month_names, 'period_names': period_names, } return patterns
--- 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) )
async def night_time(self, ctx: MyContext, night_start: str = None, night_end: str = None): """ Set the night time. Only some exclusive ducks spawn during the night. Times are specified in UTC. The bot does *not* honor daylight savings time (DST). You might need to edit this setting twice a year if you care about DST """ db_channel = await get_from_db(ctx.channel) _ = await ctx.get_translate_function() language_code = await ctx.get_language_code() if night_start is not None and night_end is not None: time_format = str( get_time_format(locale=language_code, format='medium')) time_example = format_time(datetime.datetime.now(), locale=language_code, format='medium') try: parsed_night_start = parse_time(night_start, locale=language_code) except IndexError: await ctx.send( _( "❌ I'm sorry, I couldn't understand the time you entered for night_start. " "I'm looking for something following this format: `{time_format}` (ex: `{time_example}`)", time_format=time_format, time_example=time_example)) return False seconds_night_start = parsed_night_start.hour * HOUR + parsed_night_start.minute * MINUTE + parsed_night_start.second * SECOND try: parsed_night_end = parse_time(night_end, locale=language_code) except IndexError: await ctx.send( _( "❌ I'm sorry, I couldn't understand the time you entered for night_end. " "I'm looking for something following this format: `{time_format}` (ex: `{time_example}`)", time_format=time_format, time_example=time_example)) return False seconds_night_end = parsed_night_end.hour * HOUR + parsed_night_end.minute * MINUTE + parsed_night_end.second * SECOND db_channel.night_start_at = seconds_night_start db_channel.night_end_at = seconds_night_end await db_channel.save() sun, duration_of_night, time_left_sun = await compute_sun_state( ctx.channel) duration_of_night_td = format_timedelta( datetime.timedelta(seconds=duration_of_night), locale=language_code) time_left_sun_td = format_timedelta( datetime.timedelta(seconds=time_left_sun), locale=language_code, add_direction=True) if duration_of_night == 0: await ctx.send( _( "On {channel.mention}, it's currently daytime. The day will last forever.", channel=ctx.channel, )) elif sun == "day": await ctx.send( _( "On {channel.mention}, it's currently daytime, and night will fall {time_left_sun_td}. " "Night will last for {duration_of_night_td}.", channel=ctx.channel, time_left_sun_td=time_left_sun_td, duration_of_night_td=duration_of_night_td)) else: await ctx.send( _( "On {channel.mention}, it's currently nighttime, and the sun will rise {time_left_sun_td}. " "A full night will last for {duration_of_night_td}.", channel=ctx.channel, time_left_sun_td=time_left_sun_td, duration_of_night_td=duration_of_night_td))
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) )
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, }
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))