cmlenz@3: # -*- coding: utf-8 -*- cmlenz@3: # cmlenz@3: # Copyright (C) 2007 Edgewall Software cmlenz@3: # All rights reserved. cmlenz@3: # cmlenz@3: # This software is licensed as described in the file COPYING, which cmlenz@3: # you should have received as part of this distribution. The terms cmlenz@3: # are also available at http://babel.edgewall.org/wiki/License. cmlenz@3: # cmlenz@3: # This software consists of voluntary contributions made by many cmlenz@3: # individuals. For the exact contribution history, see the revision cmlenz@3: # history and logs, available at http://babel.edgewall.org/log/. cmlenz@3: cmlenz@3: """Locale dependent formatting and parsing of dates and times. cmlenz@3: cmlenz@3: The default locale for the functions in this module is determined by the cmlenz@3: following environment variables, in that order: cmlenz@3: cmlenz@3: * ``LC_TIME``, cmlenz@3: * ``LC_ALL``, and cmlenz@3: * ``LANG`` cmlenz@3: """ cmlenz@3: cmlenz@396: from __future__ import division jruigrok@517: from datetime import date, datetime, time, timedelta cmlenz@40: import re cmlenz@3: cmlenz@235: from babel.core import default_locale, get_global, Locale cmlenz@41: from babel.util import UTC cmlenz@3: cmlenz@396: __all__ = ['format_date', 'format_datetime', 'format_time', 'format_timedelta', cmlenz@235: 'get_timezone_name', 'parse_date', 'parse_datetime', 'parse_time'] cmlenz@3: __docformat__ = 'restructuredtext en' cmlenz@3: cmlenz@74: LC_TIME = default_locale('LC_TIME') cmlenz@3: cmlenz@35: # Aliases for use in scopes where the modules are shadowed by local variables cmlenz@35: date_ = date cmlenz@35: datetime_ = datetime cmlenz@35: time_ = time cmlenz@35: cmlenz@3: def get_period_names(locale=LC_TIME): cmlenz@3: """Return the names for day periods (AM/PM) used by the locale. cmlenz@3: cmlenz@3: >>> get_period_names(locale='en_US')['am'] cmlenz@3: u'AM' cmlenz@3: cmlenz@3: :param locale: the `Locale` object, or a locale string cmlenz@3: :return: the dictionary of period names cmlenz@3: :rtype: `dict` cmlenz@3: """ cmlenz@3: return Locale.parse(locale).periods cmlenz@3: cmlenz@3: def get_day_names(width='wide', context='format', locale=LC_TIME): cmlenz@3: """Return the day names used by the locale for the specified format. cmlenz@3: cmlenz@3: >>> get_day_names('wide', locale='en_US')[1] cmlenz@17: u'Tuesday' cmlenz@3: >>> get_day_names('abbreviated', locale='es')[1] cmlenz@17: u'mar' cmlenz@3: >>> get_day_names('narrow', context='stand-alone', locale='de_DE')[1] cmlenz@17: u'D' cmlenz@3: cmlenz@3: :param width: the width to use, one of "wide", "abbreviated", or "narrow" cmlenz@3: :param context: the context, either "format" or "stand-alone" cmlenz@3: :param locale: the `Locale` object, or a locale string cmlenz@3: :return: the dictionary of day names cmlenz@3: :rtype: `dict` cmlenz@3: """ cmlenz@3: return Locale.parse(locale).days[context][width] cmlenz@3: cmlenz@3: def get_month_names(width='wide', context='format', locale=LC_TIME): cmlenz@3: """Return the month names used by the locale for the specified format. cmlenz@3: cmlenz@3: >>> get_month_names('wide', locale='en_US')[1] cmlenz@3: u'January' cmlenz@3: >>> get_month_names('abbreviated', locale='es')[1] cmlenz@3: u'ene' cmlenz@3: >>> get_month_names('narrow', context='stand-alone', locale='de_DE')[1] cmlenz@3: u'J' cmlenz@3: cmlenz@3: :param width: the width to use, one of "wide", "abbreviated", or "narrow" cmlenz@3: :param context: the context, either "format" or "stand-alone" cmlenz@3: :param locale: the `Locale` object, or a locale string cmlenz@3: :return: the dictionary of month names cmlenz@3: :rtype: `dict` cmlenz@3: """ cmlenz@3: return Locale.parse(locale).months[context][width] cmlenz@3: cmlenz@3: def get_quarter_names(width='wide', context='format', locale=LC_TIME): cmlenz@3: """Return the quarter names used by the locale for the specified format. cmlenz@3: cmlenz@3: >>> get_quarter_names('wide', locale='en_US')[1] cmlenz@3: u'1st quarter' cmlenz@3: >>> get_quarter_names('abbreviated', locale='de_DE')[1] cmlenz@3: u'Q1' cmlenz@3: cmlenz@3: :param width: the width to use, one of "wide", "abbreviated", or "narrow" cmlenz@3: :param context: the context, either "format" or "stand-alone" cmlenz@3: :param locale: the `Locale` object, or a locale string cmlenz@3: :return: the dictionary of quarter names cmlenz@3: :rtype: `dict` cmlenz@3: """ cmlenz@3: return Locale.parse(locale).quarters[context][width] cmlenz@3: cmlenz@3: def get_era_names(width='wide', locale=LC_TIME): cmlenz@3: """Return the era names used by the locale for the specified format. cmlenz@3: cmlenz@3: >>> get_era_names('wide', locale='en_US')[1] cmlenz@3: u'Anno Domini' cmlenz@3: >>> get_era_names('abbreviated', locale='de_DE')[1] cmlenz@3: u'n. Chr.' cmlenz@3: cmlenz@235: :param width: the width to use, either "wide", "abbreviated", or "narrow" cmlenz@3: :param locale: the `Locale` object, or a locale string cmlenz@3: :return: the dictionary of era names cmlenz@3: :rtype: `dict` cmlenz@3: """ cmlenz@3: return Locale.parse(locale).eras[width] cmlenz@3: cmlenz@3: def get_date_format(format='medium', locale=LC_TIME): cmlenz@3: """Return the date formatting patterns used by the locale for the specified cmlenz@3: format. cmlenz@3: cmlenz@3: >>> get_date_format(locale='en_US') jruigrok@432: cmlenz@3: >>> get_date_format('full', locale='de_DE') jruigrok@432: cmlenz@3: cmlenz@3: :param format: the format to use, one of "full", "long", "medium", or cmlenz@3: "short" cmlenz@3: :param locale: the `Locale` object, or a locale string cmlenz@3: :return: the date format pattern cmlenz@35: :rtype: `DateTimePattern` cmlenz@3: """ cmlenz@3: return Locale.parse(locale).date_formats[format] cmlenz@3: cmlenz@35: def get_datetime_format(format='medium', locale=LC_TIME): cmlenz@35: """Return the datetime formatting patterns used by the locale for the cmlenz@35: specified format. cmlenz@35: cmlenz@35: >>> get_datetime_format(locale='en_US') cmlenz@35: u'{1} {0}' cmlenz@35: cmlenz@35: :param format: the format to use, one of "full", "long", "medium", or cmlenz@35: "short" cmlenz@35: :param locale: the `Locale` object, or a locale string cmlenz@35: :return: the datetime format pattern cmlenz@35: :rtype: `unicode` cmlenz@35: """ cmlenz@35: patterns = Locale.parse(locale).datetime_formats cmlenz@35: if format not in patterns: cmlenz@35: format = None cmlenz@35: return patterns[format] cmlenz@35: cmlenz@3: def get_time_format(format='medium', locale=LC_TIME): cmlenz@3: """Return the time formatting patterns used by the locale for the specified cmlenz@3: format. cmlenz@3: cmlenz@3: >>> get_time_format(locale='en_US') cmlenz@14: cmlenz@3: >>> get_time_format('full', locale='de_DE') jruigrok@432: cmlenz@3: cmlenz@3: :param format: the format to use, one of "full", "long", "medium", or cmlenz@3: "short" cmlenz@3: :param locale: the `Locale` object, or a locale string cmlenz@3: :return: the time format pattern cmlenz@35: :rtype: `DateTimePattern` cmlenz@3: """ cmlenz@3: return Locale.parse(locale).time_formats[format] cmlenz@3: cmlenz@235: def get_timezone_gmt(datetime=None, width='long', locale=LC_TIME): cmlenz@235: """Return the timezone associated with the given `datetime` object formatted cmlenz@235: as string indicating the offset from GMT. cmlenz@235: cmlenz@235: >>> dt = datetime(2007, 4, 1, 15, 30) cmlenz@249: >>> get_timezone_gmt(dt, locale='en') cmlenz@235: u'GMT+00:00' cmlenz@235: cmlenz@235: >>> from pytz import timezone cmlenz@235: >>> tz = timezone('America/Los_Angeles') cmlenz@235: >>> dt = datetime(2007, 4, 1, 15, 30, tzinfo=tz) cmlenz@249: >>> get_timezone_gmt(dt, locale='en') cmlenz@235: u'GMT-08:00' cmlenz@249: >>> get_timezone_gmt(dt, 'short', locale='en') cmlenz@235: u'-0800' cmlenz@235: cmlenz@377: The long format depends on the locale, for example in France the acronym cmlenz@377: UTC string is used instead of GMT: cmlenz@235: cmlenz@235: >>> get_timezone_gmt(dt, 'long', locale='fr_FR') cmlenz@377: u'UTC-08:00' cmlenz@235: cmlenz@249: :param datetime: the ``datetime`` object; if `None`, the current date and cmlenz@350: time in UTC is used cmlenz@235: :param width: either "long" or "short" cmlenz@235: :param locale: the `Locale` object, or a locale string cmlenz@235: :return: the GMT offset representation of the timezone cmlenz@235: :rtype: `unicode` cmlenz@235: :since: version 0.9 cmlenz@235: """ cmlenz@235: if datetime is None: cmlenz@350: datetime = datetime_.utcnow() cmlenz@235: elif isinstance(datetime, (int, long)): cmlenz@350: datetime = datetime_.utcfromtimestamp(datetime).time() cmlenz@235: if datetime.tzinfo is None: cmlenz@235: datetime = datetime.replace(tzinfo=UTC) cmlenz@235: locale = Locale.parse(locale) cmlenz@235: cmlenz@457: offset = datetime.tzinfo.utcoffset(datetime) cmlenz@235: seconds = offset.days * 24 * 60 * 60 + offset.seconds cmlenz@235: hours, seconds = divmod(seconds, 3600) cmlenz@235: if width == 'short': cmlenz@235: pattern = u'%+03d%02d' cmlenz@235: else: cmlenz@235: pattern = locale.zone_formats['gmt'] % '%+03d:%02d' cmlenz@235: return pattern % (hours, seconds // 60) cmlenz@235: cmlenz@235: def get_timezone_location(dt_or_tzinfo=None, locale=LC_TIME): cmlenz@235: """Return a representation of the given timezone using "location format". cmlenz@235: cmlenz@235: The result depends on both the local display name of the country and the cmlenz@235: city assocaited with the time zone: cmlenz@235: cmlenz@235: >>> from pytz import timezone cmlenz@235: >>> tz = timezone('America/St_Johns') cmlenz@235: >>> get_timezone_location(tz, locale='de_DE') cmlenz@235: u"Kanada (St. John's)" cmlenz@235: >>> tz = timezone('America/Mexico_City') cmlenz@235: >>> get_timezone_location(tz, locale='de_DE') cmlenz@235: u'Mexiko (Mexiko-Stadt)' cmlenz@235: cmlenz@235: If the timezone is associated with a country that uses only a single cmlenz@235: timezone, just the localized country name is returned: cmlenz@235: cmlenz@235: >>> tz = timezone('Europe/Berlin') cmlenz@235: >>> get_timezone_name(tz, locale='de_DE') cmlenz@235: u'Deutschland' cmlenz@235: cmlenz@235: :param dt_or_tzinfo: the ``datetime`` or ``tzinfo`` object that determines cmlenz@235: the timezone; if `None`, the current date and time in cmlenz@235: UTC is assumed cmlenz@235: :param locale: the `Locale` object, or a locale string cmlenz@235: :return: the localized timezone name using location format cmlenz@235: :rtype: `unicode` cmlenz@235: :since: version 0.9 cmlenz@235: """ cmlenz@235: if dt_or_tzinfo is None or isinstance(dt_or_tzinfo, (int, long)): cmlenz@235: dt = None cmlenz@235: tzinfo = UTC cmlenz@235: elif isinstance(dt_or_tzinfo, (datetime, time)): cmlenz@235: dt = dt_or_tzinfo cmlenz@235: if dt.tzinfo is not None: cmlenz@235: tzinfo = dt.tzinfo cmlenz@235: else: cmlenz@235: tzinfo = UTC cmlenz@235: else: cmlenz@235: dt = None cmlenz@235: tzinfo = dt_or_tzinfo cmlenz@235: locale = Locale.parse(locale) cmlenz@235: cmlenz@235: if hasattr(tzinfo, 'zone'): cmlenz@235: zone = tzinfo.zone cmlenz@235: else: cmlenz@235: zone = tzinfo.tzname(dt or datetime.utcnow()) cmlenz@235: cmlenz@235: # Get the canonical time-zone code cmlenz@235: zone = get_global('zone_aliases').get(zone, zone) cmlenz@235: cmlenz@235: info = locale.time_zones.get(zone, {}) cmlenz@235: cmlenz@235: # Otherwise, if there is only one timezone for the country, return the cmlenz@235: # localized country name cmlenz@235: region_format = locale.zone_formats['region'] cmlenz@235: territory = get_global('zone_territories').get(zone) cmlenz@256: if territory not in locale.territories: cmlenz@256: territory = 'ZZ' # invalid/unknown cmlenz@235: territory_name = locale.territories[territory] cmlenz@256: if territory and len(get_global('territory_zones').get(territory, [])) == 1: cmlenz@235: return region_format % (territory_name) cmlenz@235: cmlenz@235: # Otherwise, include the city in the output cmlenz@235: fallback_format = locale.zone_formats['fallback'] cmlenz@235: if 'city' in info: cmlenz@235: city_name = info['city'] cmlenz@235: else: cmlenz@347: metazone = get_global('meta_zones').get(zone) cmlenz@347: metazone_info = locale.meta_zones.get(metazone, {}) cmlenz@347: if 'city' in metazone_info: cmlenz@347: city_name = metainfo['city'] cmlenz@347: elif '/' in zone: cmlenz@347: city_name = zone.split('/', 1)[1].replace('_', ' ') cmlenz@347: else: cmlenz@347: city_name = zone.replace('_', ' ') cmlenz@235: cmlenz@235: return region_format % (fallback_format % { cmlenz@235: '0': city_name, cmlenz@235: '1': territory_name cmlenz@235: }) cmlenz@235: cmlenz@235: def get_timezone_name(dt_or_tzinfo=None, width='long', uncommon=False, cmlenz@235: locale=LC_TIME): cmlenz@235: r"""Return the localized display name for the given timezone. The timezone cmlenz@235: may be specified using a ``datetime`` or `tzinfo` object. cmlenz@235: cmlenz@235: >>> from pytz import timezone cmlenz@235: >>> dt = time(15, 30, tzinfo=timezone('America/Los_Angeles')) cmlenz@235: >>> get_timezone_name(dt, locale='en_US') cmlenz@235: u'Pacific Standard Time' cmlenz@235: >>> get_timezone_name(dt, width='short', locale='en_US') cmlenz@235: u'PST' cmlenz@235: cmlenz@235: If this function gets passed only a `tzinfo` object and no concrete cmlenz@235: `datetime`, the returned display name is indenpendent of daylight savings cmlenz@235: time. This can be used for example for selecting timezones, or to set the cmlenz@235: time of events that recur across DST changes: cmlenz@235: cmlenz@235: >>> tz = timezone('America/Los_Angeles') cmlenz@235: >>> get_timezone_name(tz, locale='en_US') cmlenz@235: u'Pacific Time' cmlenz@235: >>> get_timezone_name(tz, 'short', locale='en_US') cmlenz@235: u'PT' cmlenz@235: cmlenz@235: If no localized display name for the timezone is available, and the timezone cmlenz@235: is associated with a country that uses only a single timezone, the name of cmlenz@235: that country is returned, formatted according to the locale: cmlenz@235: cmlenz@235: >>> tz = timezone('Europe/Berlin') cmlenz@235: >>> get_timezone_name(tz, locale='de_DE') cmlenz@235: u'Deutschland' cmlenz@235: >>> get_timezone_name(tz, locale='pt_BR') cmlenz@235: u'Hor\xe1rio Alemanha' cmlenz@235: cmlenz@235: On the other hand, if the country uses multiple timezones, the city is also cmlenz@235: included in the representation: cmlenz@235: cmlenz@235: >>> tz = timezone('America/St_Johns') cmlenz@235: >>> get_timezone_name(tz, locale='de_DE') cmlenz@235: u"Kanada (St. John's)" cmlenz@235: cmlenz@235: The `uncommon` parameter can be set to `True` to enable the use of timezone cmlenz@235: representations that are not commonly used by the requested locale. For jruigrok@453: example, while in French the central European timezone is usually jruigrok@325: abbreviated as "HEC", in Canadian French, this abbreviation is not in jruigrok@325: common use, so a generic name would be chosen by default: cmlenz@235: cmlenz@235: >>> tz = timezone('Europe/Paris') cmlenz@235: >>> get_timezone_name(tz, 'short', locale='fr_CA') cmlenz@235: u'France' cmlenz@235: >>> get_timezone_name(tz, 'short', uncommon=True, locale='fr_CA') cmlenz@235: u'HEC' cmlenz@235: cmlenz@235: :param dt_or_tzinfo: the ``datetime`` or ``tzinfo`` object that determines cmlenz@235: the timezone; if a ``tzinfo`` object is used, the cmlenz@235: resulting display name will be generic, i.e. cmlenz@235: independent of daylight savings time; if `None`, the cmlenz@235: current date in UTC is assumed cmlenz@235: :param width: either "long" or "short" cmlenz@235: :param uncommon: whether even uncommon timezone abbreviations should be used cmlenz@235: :param locale: the `Locale` object, or a locale string cmlenz@235: :return: the timezone display name cmlenz@235: :rtype: `unicode` cmlenz@235: :since: version 0.9 cmlenz@235: :see: `LDML Appendix J: Time Zone Display Names cmlenz@235: `_ cmlenz@235: """ cmlenz@235: if dt_or_tzinfo is None or isinstance(dt_or_tzinfo, (int, long)): cmlenz@235: dt = None cmlenz@235: tzinfo = UTC cmlenz@258: elif isinstance(dt_or_tzinfo, (datetime, time)): cmlenz@235: dt = dt_or_tzinfo cmlenz@235: if dt.tzinfo is not None: cmlenz@235: tzinfo = dt.tzinfo cmlenz@235: else: cmlenz@235: tzinfo = UTC cmlenz@235: else: cmlenz@235: dt = None cmlenz@235: tzinfo = dt_or_tzinfo cmlenz@235: locale = Locale.parse(locale) cmlenz@235: cmlenz@235: if hasattr(tzinfo, 'zone'): cmlenz@235: zone = tzinfo.zone cmlenz@235: else: cmlenz@350: zone = tzinfo.tzname(dt) cmlenz@235: cmlenz@235: # Get the canonical time-zone code cmlenz@235: zone = get_global('zone_aliases').get(zone, zone) cmlenz@235: cmlenz@235: info = locale.time_zones.get(zone, {}) cmlenz@235: # Try explicitly translated zone names first cmlenz@235: if width in info: cmlenz@235: if dt is None: cmlenz@235: field = 'generic' cmlenz@235: else: cmlenz@350: dst = tzinfo.dst(dt) cmlenz@350: if dst is None: cmlenz@350: field = 'generic' cmlenz@350: elif dst == 0: cmlenz@350: field = 'standard' cmlenz@350: else: cmlenz@350: field = 'daylight' cmlenz@235: if field in info[width]: cmlenz@235: return info[width][field] cmlenz@235: cmlenz@347: metazone = get_global('meta_zones').get(zone) cmlenz@347: if metazone: cmlenz@347: metazone_info = locale.meta_zones.get(metazone, {}) cmlenz@347: if width in metazone_info and (uncommon or metazone_info.get('common')): cmlenz@235: if dt is None: cmlenz@235: field = 'generic' cmlenz@235: else: cmlenz@235: field = tzinfo.dst(dt) and 'daylight' or 'standard' cmlenz@347: if field in metazone_info[width]: cmlenz@347: return metazone_info[width][field] cmlenz@235: cmlenz@235: # If we have a concrete datetime, we assume that the result can't be cmlenz@235: # independent of daylight savings time, so we return the GMT offset cmlenz@235: if dt is not None: cmlenz@255: return get_timezone_gmt(dt, width=width, locale=locale) cmlenz@235: cmlenz@235: return get_timezone_location(dt_or_tzinfo, locale=locale) cmlenz@235: cmlenz@35: def format_date(date=None, format='medium', locale=LC_TIME): cmlenz@103: """Return a date formatted according to the given pattern. cmlenz@3: cmlenz@3: >>> d = date(2007, 04, 01) cmlenz@3: >>> format_date(d, locale='en_US') cmlenz@3: u'Apr 1, 2007' cmlenz@3: >>> format_date(d, format='full', locale='de_DE') cmlenz@3: u'Sonntag, 1. April 2007' cmlenz@3: cmlenz@18: If you don't want to use the locale default formats, you can specify a cmlenz@18: custom date pattern: cmlenz@18: cmlenz@31: >>> format_date(d, "EEE, MMM d, ''yy", locale='en') cmlenz@18: u"Sun, Apr 1, '07" cmlenz@18: cmlenz@35: :param date: the ``date`` or ``datetime`` object; if `None`, the current cmlenz@35: date is used cmlenz@18: :param format: one of "full", "long", "medium", or "short", or a custom cmlenz@18: date/time pattern cmlenz@21: :param locale: a `Locale` object or a locale identifier cmlenz@3: :rtype: `unicode` cmlenz@21: cmlenz@21: :note: If the pattern contains time fields, an `AttributeError` will be cmlenz@21: raised when trying to apply the formatting. This is also true if cmlenz@21: the value of ``date`` parameter is actually a ``datetime`` object, cmlenz@21: as this function automatically converts that to a ``date``. cmlenz@3: """ cmlenz@35: if date is None: cmlenz@35: date = date_.today() cmlenz@35: elif isinstance(date, datetime): cmlenz@20: date = date.date() cmlenz@36: cmlenz@3: locale = Locale.parse(locale) cmlenz@3: if format in ('full', 'long', 'medium', 'short'): cmlenz@3: format = get_date_format(format, locale=locale) cmlenz@3: pattern = parse_pattern(format) jruigrok@504: return pattern.apply(date, locale) cmlenz@3: cmlenz@36: def format_datetime(datetime=None, format='medium', tzinfo=None, cmlenz@36: locale=LC_TIME): jruigrok@435: r"""Return a date formatted according to the given pattern. cmlenz@3: cmlenz@35: >>> dt = datetime(2007, 04, 01, 15, 30) cmlenz@35: >>> format_datetime(dt, locale='en_US') cmlenz@35: u'Apr 1, 2007 3:30:00 PM' cmlenz@35: cmlenz@36: For any pattern requiring the display of the time-zone, the third-party cmlenz@36: ``pytz`` package is needed to explicitly specify the time-zone: cmlenz@36: cmlenz@36: >>> from pytz import timezone cmlenz@235: >>> format_datetime(dt, 'full', tzinfo=timezone('Europe/Paris'), cmlenz@235: ... locale='fr_FR') jruigrok@435: u'dimanche 1 avril 2007 17:30:00 Heure avanc\xe9e de l\u2019Europe centrale' cmlenz@36: >>> format_datetime(dt, "yyyy.MM.dd G 'at' HH:mm:ss zzz", cmlenz@36: ... tzinfo=timezone('US/Eastern'), locale='en') cmlenz@36: u'2007.04.01 AD at 11:30:00 EDT' cmlenz@36: cmlenz@35: :param datetime: the `datetime` object; if `None`, the current date and cmlenz@35: time is used cmlenz@18: :param format: one of "full", "long", "medium", or "short", or a custom cmlenz@18: date/time pattern cmlenz@31: :param tzinfo: the timezone to apply to the time for display cmlenz@21: :param locale: a `Locale` object or a locale identifier cmlenz@3: :rtype: `unicode` cmlenz@3: """ cmlenz@35: if datetime is None: cmlenz@350: datetime = datetime_.utcnow() cmlenz@36: elif isinstance(datetime, (int, long)): cmlenz@378: datetime = datetime_.utcfromtimestamp(datetime) cmlenz@36: elif isinstance(datetime, time): cmlenz@36: datetime = datetime_.combine(date.today(), datetime) cmlenz@36: if datetime.tzinfo is None: cmlenz@36: datetime = datetime.replace(tzinfo=UTC) cmlenz@36: if tzinfo is not None: cmlenz@36: datetime = datetime.astimezone(tzinfo) cmlenz@103: if hasattr(tzinfo, 'normalize'): # pytz cmlenz@36: datetime = tzinfo.normalize(datetime) cmlenz@36: cmlenz@20: locale = Locale.parse(locale) cmlenz@20: if format in ('full', 'long', 'medium', 'short'): cmlenz@35: return get_datetime_format(format, locale=locale) \ cmlenz@36: .replace('{0}', format_time(datetime, format, tzinfo=None, cmlenz@35: locale=locale)) \ cmlenz@35: .replace('{1}', format_date(datetime, format, locale=locale)) cmlenz@35: else: cmlenz@35: return parse_pattern(format).apply(datetime, locale) cmlenz@3: cmlenz@36: def format_time(time=None, format='medium', tzinfo=None, locale=LC_TIME): jruigrok@435: r"""Return a time formatted according to the given pattern. cmlenz@3: cmlenz@3: >>> t = time(15, 30) cmlenz@3: >>> format_time(t, locale='en_US') cmlenz@3: u'3:30:00 PM' cmlenz@3: >>> format_time(t, format='short', locale='de_DE') cmlenz@3: u'15:30' cmlenz@3: cmlenz@18: If you don't want to use the locale default formats, you can specify a cmlenz@18: custom time pattern: cmlenz@18: cmlenz@18: >>> format_time(t, "hh 'o''clock' a", locale='en') cmlenz@18: u"03 o'clock PM" cmlenz@18: cmlenz@31: For any pattern requiring the display of the time-zone, the third-party cmlenz@31: ``pytz`` package is needed to explicitly specify the time-zone: cmlenz@31: cmlenz@103: >>> from pytz import timezone cmlenz@350: >>> t = datetime(2007, 4, 1, 15, 30) cmlenz@350: >>> tzinfo = timezone('Europe/Paris') cmlenz@350: >>> t = tzinfo.localize(t) cmlenz@350: >>> format_time(t, format='full', tzinfo=tzinfo, locale='fr_FR') jruigrok@435: u'15:30:00 Heure avanc\xe9e de l\u2019Europe centrale' cmlenz@36: >>> format_time(t, "hh 'o''clock' a, zzzz", tzinfo=timezone('US/Eastern'), cmlenz@36: ... locale='en') cmlenz@350: u"09 o'clock AM, Eastern Daylight Time" cmlenz@350: cmlenz@350: As that example shows, when this function gets passed a cmlenz@350: ``datetime.datetime`` value, the actual time in the formatted string is cmlenz@350: adjusted to the timezone specified by the `tzinfo` parameter. If the cmlenz@350: ``datetime`` is "naive" (i.e. it has no associated timezone information), cmlenz@350: it is assumed to be in UTC. cmlenz@350: cmlenz@350: These timezone calculations are **not** performed if the value is of type cmlenz@350: ``datetime.time``, as without date information there's no way to determine cmlenz@350: what a given time would translate to in a different timezone without cmlenz@350: information about whether daylight savings time is in effect or not. This cmlenz@350: means that time values are left as-is, and the value of the `tzinfo` cmlenz@350: parameter is only used to display the timezone name if needed: cmlenz@350: cmlenz@350: >>> t = time(15, 30) cmlenz@350: >>> format_time(t, format='full', tzinfo=timezone('Europe/Paris'), cmlenz@350: ... locale='fr_FR') jruigrok@432: u'15:30:00 Heure normale de l\u2019Europe centrale' cmlenz@350: >>> format_time(t, format='full', tzinfo=timezone('US/Eastern'), cmlenz@350: ... locale='en_US') jruigrok@432: u'3:30:00 PM Eastern Standard Time' cmlenz@31: cmlenz@35: :param time: the ``time`` or ``datetime`` object; if `None`, the current cmlenz@350: time in UTC is used cmlenz@18: :param format: one of "full", "long", "medium", or "short", or a custom cmlenz@18: date/time pattern cmlenz@31: :param tzinfo: the time-zone to apply to the time for display cmlenz@21: :param locale: a `Locale` object or a locale identifier cmlenz@3: :rtype: `unicode` cmlenz@21: cmlenz@21: :note: If the pattern contains date fields, an `AttributeError` will be cmlenz@21: raised when trying to apply the formatting. This is also true if cmlenz@21: the value of ``time`` parameter is actually a ``datetime`` object, cmlenz@21: as this function automatically converts that to a ``time``. cmlenz@3: """ cmlenz@35: if time is None: cmlenz@350: time = datetime.utcnow() cmlenz@35: elif isinstance(time, (int, long)): cmlenz@350: time = datetime.utcfromtimestamp(time) cmlenz@31: if time.tzinfo is None: cmlenz@36: time = time.replace(tzinfo=UTC) cmlenz@350: if isinstance(time, datetime): cmlenz@350: if tzinfo is not None: cmlenz@350: time = time.astimezone(tzinfo) cmlenz@392: if hasattr(tzinfo, 'normalize'): # pytz cmlenz@350: time = tzinfo.normalize(time) cmlenz@350: time = time.timetz() cmlenz@350: elif tzinfo is not None: cmlenz@350: time = time.replace(tzinfo=tzinfo) cmlenz@36: cmlenz@3: locale = Locale.parse(locale) cmlenz@3: if format in ('full', 'long', 'medium', 'short'): cmlenz@3: format = get_time_format(format, locale=locale) cmlenz@3: return parse_pattern(format).apply(time, locale) cmlenz@3: cmlenz@392: TIMEDELTA_UNITS = ( cmlenz@392: ('year', 3600 * 24 * 365), cmlenz@392: ('month', 3600 * 24 * 30), cmlenz@392: ('week', 3600 * 24 * 7), cmlenz@392: ('day', 3600 * 24), cmlenz@392: ('hour', 3600), cmlenz@392: ('minute', 60), cmlenz@392: ('second', 1) cmlenz@392: ) cmlenz@392: cmlenz@396: def format_timedelta(delta, granularity='second', threshold=.85, locale=LC_TIME): cmlenz@392: """Return a time delta according to the rules of the given locale. cmlenz@396: cmlenz@392: >>> format_timedelta(timedelta(weeks=12), locale='en_US') jruigrok@432: u'3 mths' cmlenz@392: >>> format_timedelta(timedelta(seconds=1), locale='es') jruigrok@432: u'1 s' cmlenz@396: cmlenz@396: The granularity parameter can be provided to alter the lowest unit cmlenz@396: presented, which defaults to a second. cmlenz@392: cmlenz@396: >>> format_timedelta(timedelta(hours=3), granularity='day', cmlenz@396: ... locale='en_US') cmlenz@397: u'1 day' cmlenz@396: cmlenz@396: The threshold parameter can be used to determine at which value the cmlenz@396: presentation switches to the next higher unit. A higher threshold factor cmlenz@396: means the presentation will switch later. For example: cmlenz@396: cmlenz@396: >>> format_timedelta(timedelta(hours=23), threshold=0.9, locale='en_US') cmlenz@396: u'1 day' cmlenz@396: >>> format_timedelta(timedelta(hours=23), threshold=1.1, locale='en_US') jruigrok@432: u'23 hrs' cmlenz@396: cmlenz@392: :param delta: a ``timedelta`` object representing the time difference to cmlenz@396: format, or the delta in seconds as an `int` value cmlenz@396: :param granularity: determines the smallest unit that should be displayed, cmlenz@396: the value can be one of "year", "month", "week", "day", cmlenz@396: "hour", "minute" or "second" cmlenz@396: :param threshold: factor that determines at which point the presentation cmlenz@396: switches to the next higher unit cmlenz@396: :param locale: a `Locale` object or a locale identifier cmlenz@396: :rtype: `unicode` cmlenz@392: """ cmlenz@396: if isinstance(delta, timedelta): cmlenz@396: seconds = int((delta.days * 86400) + delta.seconds) cmlenz@396: else: cmlenz@396: seconds = delta cmlenz@392: locale = Locale.parse(locale) cmlenz@392: cmlenz@396: for unit, secs_per_unit in TIMEDELTA_UNITS: cmlenz@396: value = abs(seconds) / secs_per_unit cmlenz@396: if value >= threshold or unit == granularity: cmlenz@397: if unit == granularity and value > 0: cmlenz@397: value = max(1, value) cmlenz@396: value = int(round(value)) cmlenz@396: plural_form = locale.plural_form(value) cmlenz@392: pattern = locale._data['unit_patterns'][unit][plural_form] cmlenz@396: return pattern.replace('{0}', str(value)) cmlenz@396: cmlenz@396: return u'' cmlenz@392: cmlenz@3: def parse_date(string, locale=LC_TIME): cmlenz@40: """Parse a date from a string. cmlenz@40: cmlenz@40: This function uses the date format for the locale as a hint to determine cmlenz@40: the order in which the date fields appear in the string. cmlenz@40: cmlenz@40: >>> parse_date('4/1/04', locale='en_US') cmlenz@40: datetime.date(2004, 4, 1) cmlenz@40: >>> parse_date('01.04.2004', locale='de_DE') cmlenz@40: datetime.date(2004, 4, 1) cmlenz@40: cmlenz@40: :param string: the string containing the date cmlenz@40: :param locale: a `Locale` object or a locale identifier cmlenz@40: :return: the parsed date cmlenz@40: :rtype: `date` cmlenz@40: """ cmlenz@40: # TODO: try ISO format first? cmlenz@40: format = get_date_format(locale=locale).pattern.lower() cmlenz@40: year_idx = format.index('y') cmlenz@40: month_idx = format.index('m') cmlenz@40: if month_idx < 0: cmlenz@40: month_idx = format.index('l') cmlenz@40: day_idx = format.index('d') cmlenz@40: cmlenz@40: indexes = [(year_idx, 'Y'), (month_idx, 'M'), (day_idx, 'D')] cmlenz@40: indexes.sort() cmlenz@40: indexes = dict([(item[1], idx) for idx, item in enumerate(indexes)]) cmlenz@40: cmlenz@40: # FIXME: this currently only supports numbers, but should also support month cmlenz@40: # names, both in the requested locale, and english cmlenz@40: cmlenz@40: numbers = re.findall('(\d+)', string) cmlenz@40: year = numbers[indexes['Y']] cmlenz@40: if len(year) == 2: cmlenz@40: year = 2000 + int(year) cmlenz@40: else: cmlenz@40: year = int(year) cmlenz@40: month = int(numbers[indexes['M']]) cmlenz@40: day = int(numbers[indexes['D']]) cmlenz@40: if month > 12: cmlenz@40: month, day = day, month cmlenz@40: return date(year, month, day) cmlenz@3: cmlenz@3: def parse_datetime(string, locale=LC_TIME): cmlenz@48: """Parse a date and time from a string. cmlenz@48: cmlenz@48: This function uses the date and time formats for the locale as a hint to cmlenz@48: determine the order in which the time fields appear in the string. cmlenz@48: cmlenz@48: :param string: the string containing the date and time cmlenz@48: :param locale: a `Locale` object or a locale identifier cmlenz@48: :return: the parsed date/time cmlenz@48: :rtype: `datetime` cmlenz@48: """ cmlenz@3: raise NotImplementedError cmlenz@3: cmlenz@3: def parse_time(string, locale=LC_TIME): cmlenz@48: """Parse a time from a string. cmlenz@40: cmlenz@40: This function uses the time format for the locale as a hint to determine cmlenz@40: the order in which the time fields appear in the string. cmlenz@40: cmlenz@40: >>> parse_time('15:30:00', locale='en_US') cmlenz@40: datetime.time(15, 30) cmlenz@40: cmlenz@40: :param string: the string containing the time cmlenz@40: :param locale: a `Locale` object or a locale identifier cmlenz@40: :return: the parsed time cmlenz@40: :rtype: `time` cmlenz@40: """ cmlenz@40: # TODO: try ISO format first? cmlenz@40: format = get_time_format(locale=locale).pattern.lower() cmlenz@40: hour_idx = format.index('h') cmlenz@40: if hour_idx < 0: cmlenz@40: hour_idx = format.index('k') cmlenz@40: min_idx = format.index('m') cmlenz@40: sec_idx = format.index('s') cmlenz@40: cmlenz@40: indexes = [(hour_idx, 'H'), (min_idx, 'M'), (sec_idx, 'S')] cmlenz@40: indexes.sort() cmlenz@40: indexes = dict([(item[1], idx) for idx, item in enumerate(indexes)]) cmlenz@40: cmlenz@40: # FIXME: support 12 hour clock, and 0-based hour specification cmlenz@48: # and seconds should be optional, maybe minutes too cmlenz@48: # oh, and time-zones, of course cmlenz@40: cmlenz@40: numbers = re.findall('(\d+)', string) cmlenz@40: hour = int(numbers[indexes['H']]) cmlenz@40: minute = int(numbers[indexes['M']]) cmlenz@40: second = int(numbers[indexes['S']]) cmlenz@40: return time(hour, minute, second) cmlenz@3: cmlenz@3: cmlenz@14: class DateTimePattern(object): cmlenz@3: cmlenz@3: def __init__(self, pattern, format): cmlenz@3: self.pattern = pattern cmlenz@3: self.format = format cmlenz@3: cmlenz@3: def __repr__(self): cmlenz@3: return '<%s %r>' % (type(self).__name__, self.pattern) cmlenz@3: cmlenz@3: def __unicode__(self): cmlenz@3: return self.pattern cmlenz@3: cmlenz@3: def __mod__(self, other): aronacher@393: if type(other) is not DateTimeFormat: aronacher@393: return NotImplemented cmlenz@3: return self.format % other cmlenz@3: cmlenz@3: def apply(self, datetime, locale): cmlenz@3: return self % DateTimeFormat(datetime, locale) cmlenz@3: cmlenz@3: cmlenz@3: class DateTimeFormat(object): cmlenz@3: cmlenz@3: def __init__(self, value, locale): cmlenz@3: assert isinstance(value, (date, datetime, time)) cmlenz@31: if isinstance(value, (datetime, time)) and value.tzinfo is None: cmlenz@31: value = value.replace(tzinfo=UTC) cmlenz@3: self.value = value cmlenz@3: self.locale = Locale.parse(locale) cmlenz@3: cmlenz@3: def __getitem__(self, name): cmlenz@17: char = name[0] cmlenz@17: num = len(name) cmlenz@17: if char == 'G': cmlenz@17: return self.format_era(char, num) cmlenz@217: elif char in ('y', 'Y', 'u'): cmlenz@17: return self.format_year(char, num) cmlenz@17: elif char in ('Q', 'q'): cmlenz@17: return self.format_quarter(char, num) cmlenz@17: elif char in ('M', 'L'): cmlenz@17: return self.format_month(char, num) cmlenz@217: elif char in ('w', 'W'): cmlenz@217: return self.format_week(char, num) cmlenz@17: elif char == 'd': cmlenz@17: return self.format(self.value.day, num) cmlenz@223: elif char == 'D': cmlenz@223: return self.format_day_of_year(num) cmlenz@243: elif char == 'F': cmlenz@243: return self.format_day_of_week_in_month() cmlenz@17: elif char in ('E', 'e', 'c'): cmlenz@17: return self.format_weekday(char, num) cmlenz@17: elif char == 'a': cmlenz@17: return self.format_period(char) cmlenz@17: elif char == 'h': jonas@275: if self.value.hour % 12 == 0: jonas@275: return self.format(12, num) jonas@275: else: jonas@275: return self.format(self.value.hour % 12, num) cmlenz@17: elif char == 'H': cmlenz@17: return self.format(self.value.hour, num) cmlenz@20: elif char == 'K': jonas@275: return self.format(self.value.hour % 12, num) cmlenz@20: elif char == 'k': jonas@275: if self.value.hour == 0: jonas@275: return self.format(24, num) jonas@275: else: jonas@276: return self.format(self.value.hour, num) cmlenz@17: elif char == 'm': cmlenz@17: return self.format(self.value.minute, num) cmlenz@17: elif char == 's': cmlenz@17: return self.format(self.value.second, num) cmlenz@218: elif char == 'S': cmlenz@219: return self.format_frac_seconds(num) cmlenz@219: elif char == 'A': cmlenz@219: return self.format_milliseconds_in_day(num) cmlenz@235: elif char in ('z', 'Z', 'v', 'V'): cmlenz@31: return self.format_timezone(char, num) cmlenz@3: else: cmlenz@17: raise KeyError('Unsupported date/time field %r' % char) cmlenz@3: cmlenz@17: def format_era(self, char, num): cmlenz@3: width = {3: 'abbreviated', 4: 'wide', 5: 'narrow'}[max(3, num)] cmlenz@3: era = int(self.value.year >= 0) cmlenz@3: return get_era_names(width, self.locale)[era] cmlenz@3: cmlenz@17: def format_year(self, char, num): cmlenz@244: value = self.value.year cmlenz@244: if char.isupper(): cmlenz@244: week = self.get_week_number(self.get_day_of_year()) cmlenz@244: if week == 0: cmlenz@244: value -= 1 cmlenz@3: year = self.format(value, num) cmlenz@3: if num == 2: cmlenz@3: year = year[-2:] cmlenz@3: return year cmlenz@3: cmlenz@398: def format_quarter(self, char, num): cmlenz@398: quarter = (self.value.month - 1) // 3 + 1 cmlenz@398: if num <= 2: cmlenz@398: return ('%%0%dd' % num) % quarter cmlenz@398: width = {3: 'abbreviated', 4: 'wide', 5: 'narrow'}[num] cmlenz@398: context = {'Q': 'format', 'q': 'stand-alone'}[char] cmlenz@398: return get_quarter_names(width, context, self.locale)[quarter] cmlenz@398: cmlenz@17: def format_month(self, char, num): cmlenz@3: if num <= 2: cmlenz@3: return ('%%0%dd' % num) % self.value.month cmlenz@3: width = {3: 'abbreviated', 4: 'wide', 5: 'narrow'}[num] cmlenz@346: context = {'M': 'format', 'L': 'stand-alone'}[char] cmlenz@3: return get_month_names(width, context, self.locale)[self.value.month] cmlenz@3: cmlenz@217: def format_week(self, char, num): cmlenz@241: if char.islower(): # week of year cmlenz@244: day_of_year = self.get_day_of_year() cmlenz@244: week = self.get_week_number(day_of_year) cmlenz@242: if week == 0: cmlenz@244: date = self.value - timedelta(days=day_of_year) cmlenz@244: week = self.get_week_number(self.get_day_of_year(date), cmlenz@244: date.weekday()) cmlenz@242: return self.format(week, num) cmlenz@241: else: # week of month cmlenz@242: week = self.get_week_number(self.value.day) cmlenz@242: if week == 0: cmlenz@244: date = self.value - timedelta(days=self.value.day) cmlenz@244: week = self.get_week_number(date.day, date.weekday()) cmlenz@242: pass cmlenz@242: return '%d' % week cmlenz@217: cmlenz@17: def format_weekday(self, char, num): cmlenz@17: if num < 3: cmlenz@17: if char.islower(): cmlenz@17: value = 7 - self.locale.first_week_day + self.value.weekday() cmlenz@17: return self.format(value % 7 + 1, num) cmlenz@17: num = 3 cmlenz@17: weekday = self.value.weekday() cmlenz@17: width = {3: 'abbreviated', 4: 'wide', 5: 'narrow'}[num] cmlenz@17: context = {3: 'format', 4: 'format', 5: 'stand-alone'}[num] cmlenz@3: return get_day_names(width, context, self.locale)[weekday] cmlenz@3: cmlenz@223: def format_day_of_year(self, num): cmlenz@241: return self.format(self.get_day_of_year(), num) cmlenz@223: cmlenz@243: def format_day_of_week_in_month(self): cmlenz@396: return '%d' % ((self.value.day - 1) // 7 + 1) cmlenz@243: cmlenz@17: def format_period(self, char): jonas@275: period = {0: 'am', 1: 'pm'}[int(self.value.hour >= 12)] cmlenz@3: return get_period_names(locale=self.locale)[period] cmlenz@3: cmlenz@219: def format_frac_seconds(self, num): cmlenz@218: value = str(self.value.microsecond) cmlenz@218: return self.format(round(float('.%s' % value), num) * 10**num, num) cmlenz@218: cmlenz@219: def format_milliseconds_in_day(self, num): cmlenz@219: msecs = self.value.microsecond // 1000 + self.value.second * 1000 + \ cmlenz@219: self.value.minute * 60000 + self.value.hour * 3600000 cmlenz@219: return self.format(msecs, num) cmlenz@219: cmlenz@31: def format_timezone(self, char, num): cmlenz@235: width = {3: 'short', 4: 'long'}[max(3, num)] cmlenz@235: if char == 'z': cmlenz@235: return get_timezone_name(self.value, width, locale=self.locale) cmlenz@31: elif char == 'Z': cmlenz@249: return get_timezone_gmt(self.value, width, locale=self.locale) cmlenz@235: elif char == 'v': cmlenz@235: return get_timezone_name(self.value.tzinfo, width, cmlenz@235: locale=self.locale) cmlenz@235: elif char == 'V': cmlenz@235: if num == 1: cmlenz@235: return get_timezone_name(self.value.tzinfo, width, cmlenz@235: uncommon=True, locale=self.locale) cmlenz@235: return get_timezone_location(self.value.tzinfo, locale=self.locale) cmlenz@31: cmlenz@3: def format(self, value, length): cmlenz@3: return ('%%0%dd' % length) % value cmlenz@3: cmlenz@244: def get_day_of_year(self, date=None): cmlenz@244: if date is None: cmlenz@244: date = self.value cmlenz@244: return (date - date_(date.year, 1, 1)).days + 1 cmlenz@241: cmlenz@244: def get_week_number(self, day_of_period, day_of_week=None): cmlenz@241: """Return the number of the week of a day within a period. This may be cmlenz@241: the week number in a year or the week number in a month. cmlenz@241: cmlenz@241: Usually this will return a value equal to or greater than 1, but if the cmlenz@241: first week of the period is so short that it actually counts as the last cmlenz@241: week of the previous period, this function will return 0. cmlenz@241: cmlenz@241: >>> format = DateTimeFormat(date(2006, 1, 8), Locale.parse('de_DE')) cmlenz@241: >>> format.get_week_number(6) cmlenz@241: 1 cmlenz@241: cmlenz@241: >>> format = DateTimeFormat(date(2006, 1, 8), Locale.parse('en_US')) cmlenz@241: >>> format.get_week_number(6) cmlenz@241: 2 cmlenz@241: cmlenz@241: :param day_of_period: the number of the day in the period (usually cmlenz@241: either the day of month or the day of year) cmlenz@244: :param day_of_week: the week day; if ommitted, the week day of the cmlenz@244: current date is assumed cmlenz@241: """ cmlenz@244: if day_of_week is None: cmlenz@244: day_of_week = self.value.weekday() cmlenz@244: first_day = (day_of_week - self.locale.first_week_day - cmlenz@241: day_of_period + 1) % 7 cmlenz@241: if first_day < 0: cmlenz@241: first_day += 7 cmlenz@396: week_number = (day_of_period + first_day - 1) // 7 cmlenz@241: if 7 - first_day >= self.locale.min_week_days: cmlenz@241: week_number += 1 cmlenz@241: return week_number cmlenz@241: cmlenz@3: cmlenz@3: PATTERN_CHARS = { cmlenz@17: 'G': [1, 2, 3, 4, 5], # era cmlenz@17: 'y': None, 'Y': None, 'u': None, # year cmlenz@17: 'Q': [1, 2, 3, 4], 'q': [1, 2, 3, 4], # quarter cmlenz@17: 'M': [1, 2, 3, 4, 5], 'L': [1, 2, 3, 4, 5], # month cmlenz@17: 'w': [1, 2], 'W': [1], # week cmlenz@17: 'd': [1, 2], 'D': [1, 2, 3], 'F': [1], 'g': None, # day cmlenz@17: 'E': [1, 2, 3, 4, 5], 'e': [1, 2, 3, 4, 5], 'c': [1, 3, 4, 5], # week day cmlenz@17: 'a': [1], # period cmlenz@17: 'h': [1, 2], 'H': [1, 2], 'K': [1, 2], 'k': [1, 2], # hour cmlenz@17: 'm': [1, 2], # minute cmlenz@17: 's': [1, 2], 'S': None, 'A': None, # second cmlenz@235: 'z': [1, 2, 3, 4], 'Z': [1, 2, 3, 4], 'v': [1, 4], 'V': [1, 4] # zone cmlenz@3: } cmlenz@3: cmlenz@3: def parse_pattern(pattern): cmlenz@3: """Parse date, time, and datetime format patterns. cmlenz@3: cmlenz@3: >>> parse_pattern("MMMMd").format cmlenz@3: u'%(MMMM)s%(d)s' cmlenz@3: >>> parse_pattern("MMM d, yyyy").format cmlenz@3: u'%(MMM)s %(d)s, %(yyyy)s' cmlenz@18: cmlenz@18: Pattern can contain literal strings in single quotes: cmlenz@18: cmlenz@3: >>> parse_pattern("H:mm' Uhr 'z").format cmlenz@3: u'%(H)s:%(mm)s Uhr %(z)s' cmlenz@3: cmlenz@18: An actual single quote can be used by using two adjacent single quote cmlenz@18: characters: cmlenz@18: cmlenz@18: >>> parse_pattern("hh' o''clock'").format cmlenz@18: u"%(hh)s o'clock" cmlenz@18: cmlenz@3: :param pattern: the formatting pattern to parse cmlenz@3: """ cmlenz@14: if type(pattern) is DateTimePattern: cmlenz@3: return pattern cmlenz@3: cmlenz@3: result = [] cmlenz@3: quotebuf = None cmlenz@3: charbuf = [] cmlenz@3: fieldchar = [''] cmlenz@3: fieldnum = [0] cmlenz@3: cmlenz@3: def append_chars(): cmlenz@3: result.append(''.join(charbuf).replace('%', '%%')) cmlenz@3: del charbuf[:] cmlenz@3: cmlenz@3: def append_field(): cmlenz@3: limit = PATTERN_CHARS[fieldchar[0]] cmlenz@17: if limit and fieldnum[0] not in limit: cmlenz@3: raise ValueError('Invalid length for field: %r' cmlenz@3: % (fieldchar[0] * fieldnum[0])) cmlenz@3: result.append('%%(%s)s' % (fieldchar[0] * fieldnum[0])) cmlenz@3: fieldchar[0] = '' cmlenz@3: fieldnum[0] = 0 cmlenz@3: cmlenz@18: for idx, char in enumerate(pattern.replace("''", '\0')): cmlenz@3: if quotebuf is None: cmlenz@3: if char == "'": # quote started cmlenz@3: if fieldchar[0]: cmlenz@3: append_field() cmlenz@3: elif charbuf: cmlenz@3: append_chars() cmlenz@3: quotebuf = [] cmlenz@3: elif char in PATTERN_CHARS: cmlenz@3: if charbuf: cmlenz@3: append_chars() cmlenz@3: if char == fieldchar[0]: cmlenz@3: fieldnum[0] += 1 cmlenz@3: else: cmlenz@3: if fieldchar[0]: cmlenz@3: append_field() cmlenz@3: fieldchar[0] = char cmlenz@3: fieldnum[0] = 1 cmlenz@3: else: cmlenz@3: if fieldchar[0]: cmlenz@3: append_field() cmlenz@3: charbuf.append(char) cmlenz@3: cmlenz@3: elif quotebuf is not None: cmlenz@18: if char == "'": # end of quote cmlenz@3: charbuf.extend(quotebuf) cmlenz@3: quotebuf = None cmlenz@3: else: # inside quote cmlenz@3: quotebuf.append(char) cmlenz@3: cmlenz@3: if fieldchar[0]: cmlenz@3: append_field() cmlenz@3: elif charbuf: cmlenz@3: append_chars() cmlenz@3: cmlenz@18: return DateTimePattern(pattern, u''.join(result).replace('\0', "'"))