Mercurial > babel > old > babel-test
annotate babel/dates.py @ 511:f2098e9c05b4 stable-0.9.x
Fix bad check in format_time (closes #257), reported with patch and tests by jomae
author | fschwarz |
---|---|
date | Fri, 04 Mar 2011 22:34:14 +0000 |
parents | 3295127550fe |
children | 790d49d8ba30 |
rev | line source |
---|---|
1 | 1 # -*- coding: utf-8 -*- |
2 # | |
3 # Copyright (C) 2007 Edgewall Software | |
4 # All rights reserved. | |
5 # | |
6 # This software is licensed as described in the file COPYING, which | |
7 # you should have received as part of this distribution. The terms | |
8 # are also available at http://babel.edgewall.org/wiki/License. | |
9 # | |
10 # This software consists of voluntary contributions made by many | |
11 # individuals. For the exact contribution history, see the revision | |
12 # history and logs, available at http://babel.edgewall.org/log/. | |
13 | |
14 """Locale dependent formatting and parsing of dates and times. | |
15 | |
16 The default locale for the functions in this module is determined by the | |
17 following environment variables, in that order: | |
18 | |
19 * ``LC_TIME``, | |
20 * ``LC_ALL``, and | |
21 * ``LANG`` | |
22 """ | |
23 | |
29 | 24 from datetime import date, datetime, time, timedelta, tzinfo |
38
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
25 import re |
1 | 26 |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
27 from babel.core import default_locale, get_global, Locale |
39
3b314a78015d
Move function for determining the system default locale to `babel.core`, and make it available as a class method on `Locale`.
cmlenz
parents:
38
diff
changeset
|
28 from babel.util import UTC |
1 | 29 |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
30 __all__ = ['format_date', 'format_datetime', 'format_time', |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
31 'get_timezone_name', 'parse_date', 'parse_datetime', 'parse_time'] |
1 | 32 __docformat__ = 'restructuredtext en' |
33 | |
72
4dcdb1d367ec
More explicit module-level function names in `babel.core`. Added `Locale.negotiate` class method.
cmlenz
parents:
46
diff
changeset
|
34 LC_TIME = default_locale('LC_TIME') |
1 | 35 |
33 | 36 # Aliases for use in scopes where the modules are shadowed by local variables |
37 date_ = date | |
38 datetime_ = datetime | |
39 time_ = time | |
40 | |
1 | 41 def get_period_names(locale=LC_TIME): |
42 """Return the names for day periods (AM/PM) used by the locale. | |
43 | |
44 >>> get_period_names(locale='en_US')['am'] | |
45 u'AM' | |
46 | |
47 :param locale: the `Locale` object, or a locale string | |
48 :return: the dictionary of period names | |
49 :rtype: `dict` | |
50 """ | |
51 return Locale.parse(locale).periods | |
52 | |
53 def get_day_names(width='wide', context='format', locale=LC_TIME): | |
54 """Return the day names used by the locale for the specified format. | |
55 | |
56 >>> get_day_names('wide', locale='en_US')[1] | |
15 | 57 u'Tuesday' |
1 | 58 >>> get_day_names('abbreviated', locale='es')[1] |
15 | 59 u'mar' |
1 | 60 >>> get_day_names('narrow', context='stand-alone', locale='de_DE')[1] |
15 | 61 u'D' |
1 | 62 |
63 :param width: the width to use, one of "wide", "abbreviated", or "narrow" | |
64 :param context: the context, either "format" or "stand-alone" | |
65 :param locale: the `Locale` object, or a locale string | |
66 :return: the dictionary of day names | |
67 :rtype: `dict` | |
68 """ | |
69 return Locale.parse(locale).days[context][width] | |
70 | |
71 def get_month_names(width='wide', context='format', locale=LC_TIME): | |
72 """Return the month names used by the locale for the specified format. | |
73 | |
74 >>> get_month_names('wide', locale='en_US')[1] | |
75 u'January' | |
76 >>> get_month_names('abbreviated', locale='es')[1] | |
77 u'ene' | |
78 >>> get_month_names('narrow', context='stand-alone', locale='de_DE')[1] | |
79 u'J' | |
80 | |
81 :param width: the width to use, one of "wide", "abbreviated", or "narrow" | |
82 :param context: the context, either "format" or "stand-alone" | |
83 :param locale: the `Locale` object, or a locale string | |
84 :return: the dictionary of month names | |
85 :rtype: `dict` | |
86 """ | |
87 return Locale.parse(locale).months[context][width] | |
88 | |
89 def get_quarter_names(width='wide', context='format', locale=LC_TIME): | |
90 """Return the quarter names used by the locale for the specified format. | |
91 | |
92 >>> get_quarter_names('wide', locale='en_US')[1] | |
93 u'1st quarter' | |
94 >>> get_quarter_names('abbreviated', locale='de_DE')[1] | |
95 u'Q1' | |
96 | |
97 :param width: the width to use, one of "wide", "abbreviated", or "narrow" | |
98 :param context: the context, either "format" or "stand-alone" | |
99 :param locale: the `Locale` object, or a locale string | |
100 :return: the dictionary of quarter names | |
101 :rtype: `dict` | |
102 """ | |
103 return Locale.parse(locale).quarters[context][width] | |
104 | |
105 def get_era_names(width='wide', locale=LC_TIME): | |
106 """Return the era names used by the locale for the specified format. | |
107 | |
108 >>> get_era_names('wide', locale='en_US')[1] | |
109 u'Anno Domini' | |
110 >>> get_era_names('abbreviated', locale='de_DE')[1] | |
111 u'n. Chr.' | |
112 | |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
113 :param width: the width to use, either "wide", "abbreviated", or "narrow" |
1 | 114 :param locale: the `Locale` object, or a locale string |
115 :return: the dictionary of era names | |
116 :rtype: `dict` | |
117 """ | |
118 return Locale.parse(locale).eras[width] | |
119 | |
120 def get_date_format(format='medium', locale=LC_TIME): | |
121 """Return the date formatting patterns used by the locale for the specified | |
122 format. | |
123 | |
124 >>> get_date_format(locale='en_US') | |
12
a2c54ef107c2
* Removed pkg_resources/setuptools requirement from various places.
cmlenz
parents:
8
diff
changeset
|
125 <DateTimePattern u'MMM d, yyyy'> |
1 | 126 >>> get_date_format('full', locale='de_DE') |
12
a2c54ef107c2
* Removed pkg_resources/setuptools requirement from various places.
cmlenz
parents:
8
diff
changeset
|
127 <DateTimePattern u'EEEE, d. MMMM yyyy'> |
1 | 128 |
129 :param format: the format to use, one of "full", "long", "medium", or | |
130 "short" | |
131 :param locale: the `Locale` object, or a locale string | |
132 :return: the date format pattern | |
33 | 133 :rtype: `DateTimePattern` |
1 | 134 """ |
135 return Locale.parse(locale).date_formats[format] | |
136 | |
33 | 137 def get_datetime_format(format='medium', locale=LC_TIME): |
138 """Return the datetime formatting patterns used by the locale for the | |
139 specified format. | |
140 | |
141 >>> get_datetime_format(locale='en_US') | |
142 u'{1} {0}' | |
143 | |
144 :param format: the format to use, one of "full", "long", "medium", or | |
145 "short" | |
146 :param locale: the `Locale` object, or a locale string | |
147 :return: the datetime format pattern | |
148 :rtype: `unicode` | |
149 """ | |
150 patterns = Locale.parse(locale).datetime_formats | |
151 if format not in patterns: | |
152 format = None | |
153 return patterns[format] | |
154 | |
1 | 155 def get_time_format(format='medium', locale=LC_TIME): |
156 """Return the time formatting patterns used by the locale for the specified | |
157 format. | |
158 | |
159 >>> get_time_format(locale='en_US') | |
12
a2c54ef107c2
* Removed pkg_resources/setuptools requirement from various places.
cmlenz
parents:
8
diff
changeset
|
160 <DateTimePattern u'h:mm:ss a'> |
1 | 161 >>> get_time_format('full', locale='de_DE') |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
162 <DateTimePattern u'HH:mm:ss v'> |
1 | 163 |
164 :param format: the format to use, one of "full", "long", "medium", or | |
165 "short" | |
166 :param locale: the `Locale` object, or a locale string | |
167 :return: the time format pattern | |
33 | 168 :rtype: `DateTimePattern` |
1 | 169 """ |
170 return Locale.parse(locale).time_formats[format] | |
171 | |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
172 def get_timezone_gmt(datetime=None, width='long', locale=LC_TIME): |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
173 """Return the timezone associated with the given `datetime` object formatted |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
174 as string indicating the offset from GMT. |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
175 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
176 >>> dt = datetime(2007, 4, 1, 15, 30) |
247
f3fbecf951b0
`get_timezone_gmt()` wasn't getting the locale passed in all cases, which led to test errors when the default locale wasn't configured via environment variables.
cmlenz
parents:
242
diff
changeset
|
177 >>> get_timezone_gmt(dt, locale='en') |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
178 u'GMT+00:00' |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
179 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
180 >>> from pytz import timezone |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
181 >>> tz = timezone('America/Los_Angeles') |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
182 >>> dt = datetime(2007, 4, 1, 15, 30, tzinfo=tz) |
247
f3fbecf951b0
`get_timezone_gmt()` wasn't getting the locale passed in all cases, which led to test errors when the default locale wasn't configured via environment variables.
cmlenz
parents:
242
diff
changeset
|
183 >>> get_timezone_gmt(dt, locale='en') |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
184 u'GMT-08:00' |
247
f3fbecf951b0
`get_timezone_gmt()` wasn't getting the locale passed in all cases, which led to test errors when the default locale wasn't configured via environment variables.
cmlenz
parents:
242
diff
changeset
|
185 >>> get_timezone_gmt(dt, 'short', locale='en') |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
186 u'-0800' |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
187 |
379 | 188 The long format depends on the locale, for example in France the acronym |
189 UTC string is used instead of GMT: | |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
190 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
191 >>> get_timezone_gmt(dt, 'long', locale='fr_FR') |
379 | 192 u'UTC-08:00' |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
193 |
247
f3fbecf951b0
`get_timezone_gmt()` wasn't getting the locale passed in all cases, which led to test errors when the default locale wasn't configured via environment variables.
cmlenz
parents:
242
diff
changeset
|
194 :param datetime: the ``datetime`` object; if `None`, the current date and |
349 | 195 time in UTC is used |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
196 :param width: either "long" or "short" |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
197 :param locale: the `Locale` object, or a locale string |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
198 :return: the GMT offset representation of the timezone |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
199 :rtype: `unicode` |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
200 :since: version 0.9 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
201 """ |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
202 if datetime is None: |
349 | 203 datetime = datetime_.utcnow() |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
204 elif isinstance(datetime, (int, long)): |
349 | 205 datetime = datetime_.utcfromtimestamp(datetime).time() |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
206 if datetime.tzinfo is None: |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
207 datetime = datetime.replace(tzinfo=UTC) |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
208 locale = Locale.parse(locale) |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
209 |
456 | 210 offset = datetime.tzinfo.utcoffset(datetime) |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
211 seconds = offset.days * 24 * 60 * 60 + offset.seconds |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
212 hours, seconds = divmod(seconds, 3600) |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
213 if width == 'short': |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
214 pattern = u'%+03d%02d' |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
215 else: |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
216 pattern = locale.zone_formats['gmt'] % '%+03d:%02d' |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
217 return pattern % (hours, seconds // 60) |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
218 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
219 def get_timezone_location(dt_or_tzinfo=None, locale=LC_TIME): |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
220 """Return a representation of the given timezone using "location format". |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
221 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
222 The result depends on both the local display name of the country and the |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
223 city assocaited with the time zone: |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
224 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
225 >>> from pytz import timezone |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
226 >>> tz = timezone('America/St_Johns') |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
227 >>> get_timezone_location(tz, locale='de_DE') |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
228 u"Kanada (St. John's)" |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
229 >>> tz = timezone('America/Mexico_City') |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
230 >>> get_timezone_location(tz, locale='de_DE') |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
231 u'Mexiko (Mexiko-Stadt)' |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
232 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
233 If the timezone is associated with a country that uses only a single |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
234 timezone, just the localized country name is returned: |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
235 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
236 >>> tz = timezone('Europe/Berlin') |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
237 >>> get_timezone_name(tz, locale='de_DE') |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
238 u'Deutschland' |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
239 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
240 :param dt_or_tzinfo: the ``datetime`` or ``tzinfo`` object that determines |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
241 the timezone; if `None`, the current date and time in |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
242 UTC is assumed |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
243 :param locale: the `Locale` object, or a locale string |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
244 :return: the localized timezone name using location format |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
245 :rtype: `unicode` |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
246 :since: version 0.9 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
247 """ |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
248 if dt_or_tzinfo is None or isinstance(dt_or_tzinfo, (int, long)): |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
249 dt = None |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
250 tzinfo = UTC |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
251 elif isinstance(dt_or_tzinfo, (datetime, time)): |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
252 dt = dt_or_tzinfo |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
253 if dt.tzinfo is not None: |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
254 tzinfo = dt.tzinfo |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
255 else: |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
256 tzinfo = UTC |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
257 else: |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
258 dt = None |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
259 tzinfo = dt_or_tzinfo |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
260 locale = Locale.parse(locale) |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
261 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
262 if hasattr(tzinfo, 'zone'): |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
263 zone = tzinfo.zone |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
264 else: |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
265 zone = tzinfo.tzname(dt or datetime.utcnow()) |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
266 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
267 # Get the canonical time-zone code |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
268 zone = get_global('zone_aliases').get(zone, zone) |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
269 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
270 info = locale.time_zones.get(zone, {}) |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
271 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
272 # Otherwise, if there is only one timezone for the country, return the |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
273 # localized country name |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
274 region_format = locale.zone_formats['region'] |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
275 territory = get_global('zone_territories').get(zone) |
254
04936a6812af
Fail more gracefully when formatting the timezone for an unknown/invalid territory.
cmlenz
parents:
253
diff
changeset
|
276 if territory not in locale.territories: |
04936a6812af
Fail more gracefully when formatting the timezone for an unknown/invalid territory.
cmlenz
parents:
253
diff
changeset
|
277 territory = 'ZZ' # invalid/unknown |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
278 territory_name = locale.territories[territory] |
254
04936a6812af
Fail more gracefully when formatting the timezone for an unknown/invalid territory.
cmlenz
parents:
253
diff
changeset
|
279 if territory and len(get_global('territory_zones').get(territory, [])) == 1: |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
280 return region_format % (territory_name) |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
281 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
282 # Otherwise, include the city in the output |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
283 fallback_format = locale.zone_formats['fallback'] |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
284 if 'city' in info: |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
285 city_name = info['city'] |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
286 else: |
346
faf0ead3a132
Merged revisions [358:360], [364:370], [373:378], [380:382] from [source:trunk].
cmlenz
parents:
276
diff
changeset
|
287 metazone = get_global('meta_zones').get(zone) |
faf0ead3a132
Merged revisions [358:360], [364:370], [373:378], [380:382] from [source:trunk].
cmlenz
parents:
276
diff
changeset
|
288 metazone_info = locale.meta_zones.get(metazone, {}) |
faf0ead3a132
Merged revisions [358:360], [364:370], [373:378], [380:382] from [source:trunk].
cmlenz
parents:
276
diff
changeset
|
289 if 'city' in metazone_info: |
faf0ead3a132
Merged revisions [358:360], [364:370], [373:378], [380:382] from [source:trunk].
cmlenz
parents:
276
diff
changeset
|
290 city_name = metainfo['city'] |
faf0ead3a132
Merged revisions [358:360], [364:370], [373:378], [380:382] from [source:trunk].
cmlenz
parents:
276
diff
changeset
|
291 elif '/' in zone: |
faf0ead3a132
Merged revisions [358:360], [364:370], [373:378], [380:382] from [source:trunk].
cmlenz
parents:
276
diff
changeset
|
292 city_name = zone.split('/', 1)[1].replace('_', ' ') |
faf0ead3a132
Merged revisions [358:360], [364:370], [373:378], [380:382] from [source:trunk].
cmlenz
parents:
276
diff
changeset
|
293 else: |
faf0ead3a132
Merged revisions [358:360], [364:370], [373:378], [380:382] from [source:trunk].
cmlenz
parents:
276
diff
changeset
|
294 city_name = zone.replace('_', ' ') |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
295 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
296 return region_format % (fallback_format % { |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
297 '0': city_name, |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
298 '1': territory_name |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
299 }) |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
300 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
301 def get_timezone_name(dt_or_tzinfo=None, width='long', uncommon=False, |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
302 locale=LC_TIME): |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
303 r"""Return the localized display name for the given timezone. The timezone |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
304 may be specified using a ``datetime`` or `tzinfo` object. |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
305 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
306 >>> from pytz import timezone |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
307 >>> dt = time(15, 30, tzinfo=timezone('America/Los_Angeles')) |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
308 >>> get_timezone_name(dt, locale='en_US') |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
309 u'Pacific Standard Time' |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
310 >>> get_timezone_name(dt, width='short', locale='en_US') |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
311 u'PST' |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
312 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
313 If this function gets passed only a `tzinfo` object and no concrete |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
314 `datetime`, the returned display name is indenpendent of daylight savings |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
315 time. This can be used for example for selecting timezones, or to set the |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
316 time of events that recur across DST changes: |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
317 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
318 >>> tz = timezone('America/Los_Angeles') |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
319 >>> get_timezone_name(tz, locale='en_US') |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
320 u'Pacific Time' |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
321 >>> get_timezone_name(tz, 'short', locale='en_US') |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
322 u'PT' |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
323 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
324 If no localized display name for the timezone is available, and the timezone |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
325 is associated with a country that uses only a single timezone, the name of |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
326 that country is returned, formatted according to the locale: |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
327 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
328 >>> tz = timezone('Europe/Berlin') |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
329 >>> get_timezone_name(tz, locale='de_DE') |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
330 u'Deutschland' |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
331 >>> get_timezone_name(tz, locale='pt_BR') |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
332 u'Hor\xe1rio Alemanha' |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
333 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
334 On the other hand, if the country uses multiple timezones, the city is also |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
335 included in the representation: |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
336 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
337 >>> tz = timezone('America/St_Johns') |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
338 >>> get_timezone_name(tz, locale='de_DE') |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
339 u"Kanada (St. John's)" |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
340 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
341 The `uncommon` parameter can be set to `True` to enable the use of timezone |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
342 representations that are not commonly used by the requested locale. For |
464 | 343 example, while in French the central European timezone is usually |
346
faf0ead3a132
Merged revisions [358:360], [364:370], [373:378], [380:382] from [source:trunk].
cmlenz
parents:
276
diff
changeset
|
344 abbreviated as "HEC", in Canadian French, this abbreviation is not in |
faf0ead3a132
Merged revisions [358:360], [364:370], [373:378], [380:382] from [source:trunk].
cmlenz
parents:
276
diff
changeset
|
345 common use, so a generic name would be chosen by default: |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
346 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
347 >>> tz = timezone('Europe/Paris') |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
348 >>> get_timezone_name(tz, 'short', locale='fr_CA') |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
349 u'France' |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
350 >>> get_timezone_name(tz, 'short', uncommon=True, locale='fr_CA') |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
351 u'HEC' |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
352 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
353 :param dt_or_tzinfo: the ``datetime`` or ``tzinfo`` object that determines |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
354 the timezone; if a ``tzinfo`` object is used, the |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
355 resulting display name will be generic, i.e. |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
356 independent of daylight savings time; if `None`, the |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
357 current date in UTC is assumed |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
358 :param width: either "long" or "short" |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
359 :param uncommon: whether even uncommon timezone abbreviations should be used |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
360 :param locale: the `Locale` object, or a locale string |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
361 :return: the timezone display name |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
362 :rtype: `unicode` |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
363 :since: version 0.9 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
364 :see: `LDML Appendix J: Time Zone Display Names |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
365 <http://www.unicode.org/reports/tr35/#Time_Zone_Fallback>`_ |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
366 """ |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
367 if dt_or_tzinfo is None or isinstance(dt_or_tzinfo, (int, long)): |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
368 dt = None |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
369 tzinfo = UTC |
256 | 370 elif isinstance(dt_or_tzinfo, (datetime, time)): |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
371 dt = dt_or_tzinfo |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
372 if dt.tzinfo is not None: |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
373 tzinfo = dt.tzinfo |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
374 else: |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
375 tzinfo = UTC |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
376 else: |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
377 dt = None |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
378 tzinfo = dt_or_tzinfo |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
379 locale = Locale.parse(locale) |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
380 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
381 if hasattr(tzinfo, 'zone'): |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
382 zone = tzinfo.zone |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
383 else: |
349 | 384 zone = tzinfo.tzname(dt) |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
385 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
386 # Get the canonical time-zone code |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
387 zone = get_global('zone_aliases').get(zone, zone) |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
388 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
389 info = locale.time_zones.get(zone, {}) |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
390 # Try explicitly translated zone names first |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
391 if width in info: |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
392 if dt is None: |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
393 field = 'generic' |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
394 else: |
349 | 395 dst = tzinfo.dst(dt) |
396 if dst is None: | |
397 field = 'generic' | |
398 elif dst == 0: | |
399 field = 'standard' | |
400 else: | |
401 field = 'daylight' | |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
402 if field in info[width]: |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
403 return info[width][field] |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
404 |
346
faf0ead3a132
Merged revisions [358:360], [364:370], [373:378], [380:382] from [source:trunk].
cmlenz
parents:
276
diff
changeset
|
405 metazone = get_global('meta_zones').get(zone) |
faf0ead3a132
Merged revisions [358:360], [364:370], [373:378], [380:382] from [source:trunk].
cmlenz
parents:
276
diff
changeset
|
406 if metazone: |
faf0ead3a132
Merged revisions [358:360], [364:370], [373:378], [380:382] from [source:trunk].
cmlenz
parents:
276
diff
changeset
|
407 metazone_info = locale.meta_zones.get(metazone, {}) |
faf0ead3a132
Merged revisions [358:360], [364:370], [373:378], [380:382] from [source:trunk].
cmlenz
parents:
276
diff
changeset
|
408 if width in metazone_info and (uncommon or metazone_info.get('common')): |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
409 if dt is None: |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
410 field = 'generic' |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
411 else: |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
412 field = tzinfo.dst(dt) and 'daylight' or 'standard' |
346
faf0ead3a132
Merged revisions [358:360], [364:370], [373:378], [380:382] from [source:trunk].
cmlenz
parents:
276
diff
changeset
|
413 if field in metazone_info[width]: |
faf0ead3a132
Merged revisions [358:360], [364:370], [373:378], [380:382] from [source:trunk].
cmlenz
parents:
276
diff
changeset
|
414 return metazone_info[width][field] |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
415 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
416 # If we have a concrete datetime, we assume that the result can't be |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
417 # independent of daylight savings time, so we return the GMT offset |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
418 if dt is not None: |
253
ba30864779cc
Fix for `get_timezone_name` when falling back to GMT display.
cmlenz
parents:
247
diff
changeset
|
419 return get_timezone_gmt(dt, width=width, locale=locale) |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
420 |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
421 return get_timezone_location(dt_or_tzinfo, locale=locale) |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
422 |
33 | 423 def format_date(date=None, format='medium', locale=LC_TIME): |
101
1312ad6b624d
Add wrapper class bundling the various formatting functions bound to a specific locale and time-zone.
cmlenz
parents:
72
diff
changeset
|
424 """Return a date formatted according to the given pattern. |
1 | 425 |
426 >>> d = date(2007, 04, 01) | |
427 >>> format_date(d, locale='en_US') | |
428 u'Apr 1, 2007' | |
429 >>> format_date(d, format='full', locale='de_DE') | |
430 u'Sonntag, 1. April 2007' | |
431 | |
16 | 432 If you don't want to use the locale default formats, you can specify a |
433 custom date pattern: | |
434 | |
29 | 435 >>> format_date(d, "EEE, MMM d, ''yy", locale='en') |
16 | 436 u"Sun, Apr 1, '07" |
437 | |
33 | 438 :param date: the ``date`` or ``datetime`` object; if `None`, the current |
439 date is used | |
16 | 440 :param format: one of "full", "long", "medium", or "short", or a custom |
441 date/time pattern | |
19
c0c92d11f1ab
Moved some datetime tests from doctest to unittest, to avoid breaking docutils/epydoc doctest block detection.
cmlenz
parents:
18
diff
changeset
|
442 :param locale: a `Locale` object or a locale identifier |
1 | 443 :rtype: `unicode` |
19
c0c92d11f1ab
Moved some datetime tests from doctest to unittest, to avoid breaking docutils/epydoc doctest block detection.
cmlenz
parents:
18
diff
changeset
|
444 |
c0c92d11f1ab
Moved some datetime tests from doctest to unittest, to avoid breaking docutils/epydoc doctest block detection.
cmlenz
parents:
18
diff
changeset
|
445 :note: If the pattern contains time fields, an `AttributeError` will be |
c0c92d11f1ab
Moved some datetime tests from doctest to unittest, to avoid breaking docutils/epydoc doctest block detection.
cmlenz
parents:
18
diff
changeset
|
446 raised when trying to apply the formatting. This is also true if |
c0c92d11f1ab
Moved some datetime tests from doctest to unittest, to avoid breaking docutils/epydoc doctest block detection.
cmlenz
parents:
18
diff
changeset
|
447 the value of ``date`` parameter is actually a ``datetime`` object, |
c0c92d11f1ab
Moved some datetime tests from doctest to unittest, to avoid breaking docutils/epydoc doctest block detection.
cmlenz
parents:
18
diff
changeset
|
448 as this function automatically converts that to a ``date``. |
1 | 449 """ |
33 | 450 if date is None: |
451 date = date_.today() | |
452 elif isinstance(date, datetime): | |
18
77a68f88f6bc
Started documentation for date formatting, plus some code tweaks in that area.
cmlenz
parents:
16
diff
changeset
|
453 date = date.date() |
34 | 454 |
1 | 455 locale = Locale.parse(locale) |
456 if format in ('full', 'long', 'medium', 'short'): | |
457 format = get_date_format(format, locale=locale) | |
458 pattern = parse_pattern(format) | |
503 | 459 return pattern.apply(date, locale) |
1 | 460 |
34 | 461 def format_datetime(datetime=None, format='medium', tzinfo=None, |
462 locale=LC_TIME): | |
101
1312ad6b624d
Add wrapper class bundling the various formatting functions bound to a specific locale and time-zone.
cmlenz
parents:
72
diff
changeset
|
463 """Return a date formatted according to the given pattern. |
1 | 464 |
33 | 465 >>> dt = datetime(2007, 04, 01, 15, 30) |
466 >>> format_datetime(dt, locale='en_US') | |
467 u'Apr 1, 2007 3:30:00 PM' | |
468 | |
34 | 469 For any pattern requiring the display of the time-zone, the third-party |
470 ``pytz`` package is needed to explicitly specify the time-zone: | |
471 | |
472 >>> from pytz import timezone | |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
473 >>> format_datetime(dt, 'full', tzinfo=timezone('Europe/Paris'), |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
474 ... locale='fr_FR') |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
475 u'dimanche 1 avril 2007 17:30:00 HEC' |
34 | 476 >>> format_datetime(dt, "yyyy.MM.dd G 'at' HH:mm:ss zzz", |
477 ... tzinfo=timezone('US/Eastern'), locale='en') | |
478 u'2007.04.01 AD at 11:30:00 EDT' | |
479 | |
33 | 480 :param datetime: the `datetime` object; if `None`, the current date and |
481 time is used | |
16 | 482 :param format: one of "full", "long", "medium", or "short", or a custom |
483 date/time pattern | |
29 | 484 :param tzinfo: the timezone to apply to the time for display |
19
c0c92d11f1ab
Moved some datetime tests from doctest to unittest, to avoid breaking docutils/epydoc doctest block detection.
cmlenz
parents:
18
diff
changeset
|
485 :param locale: a `Locale` object or a locale identifier |
1 | 486 :rtype: `unicode` |
487 """ | |
33 | 488 if datetime is None: |
349 | 489 datetime = datetime_.utcnow() |
34 | 490 elif isinstance(datetime, (int, long)): |
379 | 491 datetime = datetime_.utcfromtimestamp(datetime) |
34 | 492 elif isinstance(datetime, time): |
493 datetime = datetime_.combine(date.today(), datetime) | |
494 if datetime.tzinfo is None: | |
495 datetime = datetime.replace(tzinfo=UTC) | |
496 if tzinfo is not None: | |
497 datetime = datetime.astimezone(tzinfo) | |
101
1312ad6b624d
Add wrapper class bundling the various formatting functions bound to a specific locale and time-zone.
cmlenz
parents:
72
diff
changeset
|
498 if hasattr(tzinfo, 'normalize'): # pytz |
34 | 499 datetime = tzinfo.normalize(datetime) |
500 | |
18
77a68f88f6bc
Started documentation for date formatting, plus some code tweaks in that area.
cmlenz
parents:
16
diff
changeset
|
501 locale = Locale.parse(locale) |
77a68f88f6bc
Started documentation for date formatting, plus some code tweaks in that area.
cmlenz
parents:
16
diff
changeset
|
502 if format in ('full', 'long', 'medium', 'short'): |
33 | 503 return get_datetime_format(format, locale=locale) \ |
34 | 504 .replace('{0}', format_time(datetime, format, tzinfo=None, |
33 | 505 locale=locale)) \ |
506 .replace('{1}', format_date(datetime, format, locale=locale)) | |
507 else: | |
508 return parse_pattern(format).apply(datetime, locale) | |
1 | 509 |
34 | 510 def format_time(time=None, format='medium', tzinfo=None, locale=LC_TIME): |
101
1312ad6b624d
Add wrapper class bundling the various formatting functions bound to a specific locale and time-zone.
cmlenz
parents:
72
diff
changeset
|
511 """Return a time formatted according to the given pattern. |
1 | 512 |
513 >>> t = time(15, 30) | |
514 >>> format_time(t, locale='en_US') | |
515 u'3:30:00 PM' | |
516 >>> format_time(t, format='short', locale='de_DE') | |
517 u'15:30' | |
518 | |
16 | 519 If you don't want to use the locale default formats, you can specify a |
520 custom time pattern: | |
521 | |
522 >>> format_time(t, "hh 'o''clock' a", locale='en') | |
523 u"03 o'clock PM" | |
524 | |
29 | 525 For any pattern requiring the display of the time-zone, the third-party |
526 ``pytz`` package is needed to explicitly specify the time-zone: | |
527 | |
101
1312ad6b624d
Add wrapper class bundling the various formatting functions bound to a specific locale and time-zone.
cmlenz
parents:
72
diff
changeset
|
528 >>> from pytz import timezone |
349 | 529 >>> t = datetime(2007, 4, 1, 15, 30) |
530 >>> tzinfo = timezone('Europe/Paris') | |
531 >>> t = tzinfo.localize(t) | |
532 >>> format_time(t, format='full', tzinfo=tzinfo, locale='fr_FR') | |
533 u'15:30:00 HEC' | |
34 | 534 >>> format_time(t, "hh 'o''clock' a, zzzz", tzinfo=timezone('US/Eastern'), |
535 ... locale='en') | |
349 | 536 u"09 o'clock AM, Eastern Daylight Time" |
537 | |
538 As that example shows, when this function gets passed a | |
539 ``datetime.datetime`` value, the actual time in the formatted string is | |
540 adjusted to the timezone specified by the `tzinfo` parameter. If the | |
541 ``datetime`` is "naive" (i.e. it has no associated timezone information), | |
542 it is assumed to be in UTC. | |
543 | |
544 These timezone calculations are **not** performed if the value is of type | |
545 ``datetime.time``, as without date information there's no way to determine | |
546 what a given time would translate to in a different timezone without | |
547 information about whether daylight savings time is in effect or not. This | |
548 means that time values are left as-is, and the value of the `tzinfo` | |
549 parameter is only used to display the timezone name if needed: | |
550 | |
551 >>> t = time(15, 30) | |
552 >>> format_time(t, format='full', tzinfo=timezone('Europe/Paris'), | |
553 ... locale='fr_FR') | |
554 u'15:30:00 HEC' | |
555 >>> format_time(t, format='full', tzinfo=timezone('US/Eastern'), | |
556 ... locale='en_US') | |
557 u'3:30:00 PM ET' | |
29 | 558 |
33 | 559 :param time: the ``time`` or ``datetime`` object; if `None`, the current |
349 | 560 time in UTC is used |
16 | 561 :param format: one of "full", "long", "medium", or "short", or a custom |
562 date/time pattern | |
29 | 563 :param tzinfo: the time-zone to apply to the time for display |
19
c0c92d11f1ab
Moved some datetime tests from doctest to unittest, to avoid breaking docutils/epydoc doctest block detection.
cmlenz
parents:
18
diff
changeset
|
564 :param locale: a `Locale` object or a locale identifier |
1 | 565 :rtype: `unicode` |
19
c0c92d11f1ab
Moved some datetime tests from doctest to unittest, to avoid breaking docutils/epydoc doctest block detection.
cmlenz
parents:
18
diff
changeset
|
566 |
c0c92d11f1ab
Moved some datetime tests from doctest to unittest, to avoid breaking docutils/epydoc doctest block detection.
cmlenz
parents:
18
diff
changeset
|
567 :note: If the pattern contains date fields, an `AttributeError` will be |
c0c92d11f1ab
Moved some datetime tests from doctest to unittest, to avoid breaking docutils/epydoc doctest block detection.
cmlenz
parents:
18
diff
changeset
|
568 raised when trying to apply the formatting. This is also true if |
c0c92d11f1ab
Moved some datetime tests from doctest to unittest, to avoid breaking docutils/epydoc doctest block detection.
cmlenz
parents:
18
diff
changeset
|
569 the value of ``time`` parameter is actually a ``datetime`` object, |
c0c92d11f1ab
Moved some datetime tests from doctest to unittest, to avoid breaking docutils/epydoc doctest block detection.
cmlenz
parents:
18
diff
changeset
|
570 as this function automatically converts that to a ``time``. |
1 | 571 """ |
33 | 572 if time is None: |
349 | 573 time = datetime.utcnow() |
33 | 574 elif isinstance(time, (int, long)): |
349 | 575 time = datetime.utcfromtimestamp(time) |
29 | 576 if time.tzinfo is None: |
34 | 577 time = time.replace(tzinfo=UTC) |
349 | 578 if isinstance(time, datetime): |
579 if tzinfo is not None: | |
580 time = time.astimezone(tzinfo) | |
511
f2098e9c05b4
Fix bad check in format_time (closes #257), reported with patch and tests by jomae
fschwarz
parents:
503
diff
changeset
|
581 if hasattr(tzinfo, 'normalize'): # pytz |
349 | 582 time = tzinfo.normalize(time) |
583 time = time.timetz() | |
584 elif tzinfo is not None: | |
585 time = time.replace(tzinfo=tzinfo) | |
34 | 586 |
1 | 587 locale = Locale.parse(locale) |
588 if format in ('full', 'long', 'medium', 'short'): | |
589 format = get_time_format(format, locale=locale) | |
590 return parse_pattern(format).apply(time, locale) | |
591 | |
592 def parse_date(string, locale=LC_TIME): | |
38
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
593 """Parse a date from a string. |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
594 |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
595 This function uses the date format for the locale as a hint to determine |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
596 the order in which the date fields appear in the string. |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
597 |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
598 >>> parse_date('4/1/04', locale='en_US') |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
599 datetime.date(2004, 4, 1) |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
600 >>> parse_date('01.04.2004', locale='de_DE') |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
601 datetime.date(2004, 4, 1) |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
602 |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
603 :param string: the string containing the date |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
604 :param locale: a `Locale` object or a locale identifier |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
605 :return: the parsed date |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
606 :rtype: `date` |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
607 """ |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
608 # TODO: try ISO format first? |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
609 format = get_date_format(locale=locale).pattern.lower() |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
610 year_idx = format.index('y') |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
611 month_idx = format.index('m') |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
612 if month_idx < 0: |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
613 month_idx = format.index('l') |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
614 day_idx = format.index('d') |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
615 |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
616 indexes = [(year_idx, 'Y'), (month_idx, 'M'), (day_idx, 'D')] |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
617 indexes.sort() |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
618 indexes = dict([(item[1], idx) for idx, item in enumerate(indexes)]) |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
619 |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
620 # FIXME: this currently only supports numbers, but should also support month |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
621 # names, both in the requested locale, and english |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
622 |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
623 numbers = re.findall('(\d+)', string) |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
624 year = numbers[indexes['Y']] |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
625 if len(year) == 2: |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
626 year = 2000 + int(year) |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
627 else: |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
628 year = int(year) |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
629 month = int(numbers[indexes['M']]) |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
630 day = int(numbers[indexes['D']]) |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
631 if month > 12: |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
632 month, day = day, month |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
633 return date(year, month, day) |
1 | 634 |
635 def parse_datetime(string, locale=LC_TIME): | |
46 | 636 """Parse a date and time from a string. |
637 | |
638 This function uses the date and time formats for the locale as a hint to | |
639 determine the order in which the time fields appear in the string. | |
640 | |
641 :param string: the string containing the date and time | |
642 :param locale: a `Locale` object or a locale identifier | |
643 :return: the parsed date/time | |
644 :rtype: `datetime` | |
645 """ | |
1 | 646 raise NotImplementedError |
647 | |
648 def parse_time(string, locale=LC_TIME): | |
46 | 649 """Parse a time from a string. |
38
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
650 |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
651 This function uses the time format for the locale as a hint to determine |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
652 the order in which the time fields appear in the string. |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
653 |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
654 >>> parse_time('15:30:00', locale='en_US') |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
655 datetime.time(15, 30) |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
656 |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
657 :param string: the string containing the time |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
658 :param locale: a `Locale` object or a locale identifier |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
659 :return: the parsed time |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
660 :rtype: `time` |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
661 """ |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
662 # TODO: try ISO format first? |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
663 format = get_time_format(locale=locale).pattern.lower() |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
664 hour_idx = format.index('h') |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
665 if hour_idx < 0: |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
666 hour_idx = format.index('k') |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
667 min_idx = format.index('m') |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
668 sec_idx = format.index('s') |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
669 |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
670 indexes = [(hour_idx, 'H'), (min_idx, 'M'), (sec_idx, 'S')] |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
671 indexes.sort() |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
672 indexes = dict([(item[1], idx) for idx, item in enumerate(indexes)]) |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
673 |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
674 # FIXME: support 12 hour clock, and 0-based hour specification |
46 | 675 # and seconds should be optional, maybe minutes too |
676 # oh, and time-zones, of course | |
38
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
677 |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
678 numbers = re.findall('(\d+)', string) |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
679 hour = int(numbers[indexes['H']]) |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
680 minute = int(numbers[indexes['M']]) |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
681 second = int(numbers[indexes['S']]) |
a22b7656e9ae
Started implementation of datetime parsing, using a very basic approach for now.
cmlenz
parents:
34
diff
changeset
|
682 return time(hour, minute, second) |
1 | 683 |
684 | |
12
a2c54ef107c2
* Removed pkg_resources/setuptools requirement from various places.
cmlenz
parents:
8
diff
changeset
|
685 class DateTimePattern(object): |
1 | 686 |
687 def __init__(self, pattern, format): | |
688 self.pattern = pattern | |
689 self.format = format | |
690 | |
691 def __repr__(self): | |
692 return '<%s %r>' % (type(self).__name__, self.pattern) | |
693 | |
694 def __unicode__(self): | |
695 return self.pattern | |
696 | |
697 def __mod__(self, other): | |
698 assert type(other) is DateTimeFormat | |
699 return self.format % other | |
700 | |
701 def apply(self, datetime, locale): | |
702 return self % DateTimeFormat(datetime, locale) | |
703 | |
704 | |
705 class DateTimeFormat(object): | |
706 | |
707 def __init__(self, value, locale): | |
708 assert isinstance(value, (date, datetime, time)) | |
29 | 709 if isinstance(value, (datetime, time)) and value.tzinfo is None: |
710 value = value.replace(tzinfo=UTC) | |
1 | 711 self.value = value |
712 self.locale = Locale.parse(locale) | |
713 | |
714 def __getitem__(self, name): | |
15 | 715 char = name[0] |
716 num = len(name) | |
717 if char == 'G': | |
718 return self.format_era(char, num) | |
215
d37628e752c4
Dummy/stub implementation for week-in-year and week-in-month date format fields. Also, treat extended year the same as the regular year field, not even ICU seems to handle it specially.
cmlenz
parents:
129
diff
changeset
|
719 elif char in ('y', 'Y', 'u'): |
15 | 720 return self.format_year(char, num) |
721 elif char in ('Q', 'q'): | |
722 return self.format_quarter(char, num) | |
723 elif char in ('M', 'L'): | |
724 return self.format_month(char, num) | |
215
d37628e752c4
Dummy/stub implementation for week-in-year and week-in-month date format fields. Also, treat extended year the same as the regular year field, not even ICU seems to handle it specially.
cmlenz
parents:
129
diff
changeset
|
725 elif char in ('w', 'W'): |
d37628e752c4
Dummy/stub implementation for week-in-year and week-in-month date format fields. Also, treat extended year the same as the regular year field, not even ICU seems to handle it specially.
cmlenz
parents:
129
diff
changeset
|
726 return self.format_week(char, num) |
15 | 727 elif char == 'd': |
728 return self.format(self.value.day, num) | |
221
898b9450f274
Implement day-of-year date format field. Closes #49.
cmlenz
parents:
217
diff
changeset
|
729 elif char == 'D': |
898b9450f274
Implement day-of-year date format field. Closes #49.
cmlenz
parents:
217
diff
changeset
|
730 return self.format_day_of_year(num) |
241
9fedbb6f9871
Implement day-of-week-in-month field in date formatting. Closes #50.
cmlenz
parents:
240
diff
changeset
|
731 elif char == 'F': |
9fedbb6f9871
Implement day-of-week-in-month field in date formatting. Closes #50.
cmlenz
parents:
240
diff
changeset
|
732 return self.format_day_of_week_in_month() |
15 | 733 elif char in ('E', 'e', 'c'): |
734 return self.format_weekday(char, num) | |
735 elif char == 'a': | |
736 return self.format_period(char) | |
737 elif char == 'h': | |
276 | 738 if self.value.hour % 12 == 0: |
739 return self.format(12, num) | |
740 else: | |
741 return self.format(self.value.hour % 12, num) | |
15 | 742 elif char == 'H': |
743 return self.format(self.value.hour, num) | |
18
77a68f88f6bc
Started documentation for date formatting, plus some code tweaks in that area.
cmlenz
parents:
16
diff
changeset
|
744 elif char == 'K': |
276 | 745 return self.format(self.value.hour % 12, num) |
18
77a68f88f6bc
Started documentation for date formatting, plus some code tweaks in that area.
cmlenz
parents:
16
diff
changeset
|
746 elif char == 'k': |
276 | 747 if self.value.hour == 0: |
748 return self.format(24, num) | |
749 else: | |
750 return self.format(self.value.hour, num) | |
15 | 751 elif char == 'm': |
752 return self.format(self.value.minute, num) | |
753 elif char == 's': | |
754 return self.format(self.value.second, num) | |
216
1f3c3924b1b5
Support for fractional seconds field in date formatting. Closes #47.
cmlenz
parents:
215
diff
changeset
|
755 elif char == 'S': |
217 | 756 return self.format_frac_seconds(num) |
757 elif char == 'A': | |
758 return self.format_milliseconds_in_day(num) | |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
759 elif char in ('z', 'Z', 'v', 'V'): |
29 | 760 return self.format_timezone(char, num) |
1 | 761 else: |
15 | 762 raise KeyError('Unsupported date/time field %r' % char) |
1 | 763 |
15 | 764 def format_era(self, char, num): |
1 | 765 width = {3: 'abbreviated', 4: 'wide', 5: 'narrow'}[max(3, num)] |
766 era = int(self.value.year >= 0) | |
767 return get_era_names(width, self.locale)[era] | |
768 | |
15 | 769 def format_year(self, char, num): |
242
059b74719f6b
Finish implementation of day-of-year and day-of-month for now, and fix implementation of year-of-week-of-year field. Closes #46. I suspect there are still cases not entirely covered by this implementation, but those can be filed as separate tickets.
cmlenz
parents:
241
diff
changeset
|
770 value = self.value.year |
059b74719f6b
Finish implementation of day-of-year and day-of-month for now, and fix implementation of year-of-week-of-year field. Closes #46. I suspect there are still cases not entirely covered by this implementation, but those can be filed as separate tickets.
cmlenz
parents:
241
diff
changeset
|
771 if char.isupper(): |
059b74719f6b
Finish implementation of day-of-year and day-of-month for now, and fix implementation of year-of-week-of-year field. Closes #46. I suspect there are still cases not entirely covered by this implementation, but those can be filed as separate tickets.
cmlenz
parents:
241
diff
changeset
|
772 week = self.get_week_number(self.get_day_of_year()) |
059b74719f6b
Finish implementation of day-of-year and day-of-month for now, and fix implementation of year-of-week-of-year field. Closes #46. I suspect there are still cases not entirely covered by this implementation, but those can be filed as separate tickets.
cmlenz
parents:
241
diff
changeset
|
773 if week == 0: |
059b74719f6b
Finish implementation of day-of-year and day-of-month for now, and fix implementation of year-of-week-of-year field. Closes #46. I suspect there are still cases not entirely covered by this implementation, but those can be filed as separate tickets.
cmlenz
parents:
241
diff
changeset
|
774 value -= 1 |
1 | 775 year = self.format(value, num) |
776 if num == 2: | |
777 year = year[-2:] | |
778 return year | |
779 | |
397 | 780 def format_quarter(self, char, num): |
781 quarter = (self.value.month - 1) // 3 + 1 | |
782 if num <= 2: | |
783 return ('%%0%dd' % num) % quarter | |
784 width = {3: 'abbreviated', 4: 'wide', 5: 'narrow'}[num] | |
785 context = {'Q': 'format', 'q': 'stand-alone'}[char] | |
786 return get_quarter_names(width, context, self.locale)[quarter] | |
787 | |
15 | 788 def format_month(self, char, num): |
1 | 789 if num <= 2: |
790 return ('%%0%dd' % num) % self.value.month | |
791 width = {3: 'abbreviated', 4: 'wide', 5: 'narrow'}[num] | |
346
faf0ead3a132
Merged revisions [358:360], [364:370], [373:378], [380:382] from [source:trunk].
cmlenz
parents:
276
diff
changeset
|
792 context = {'M': 'format', 'L': 'stand-alone'}[char] |
1 | 793 return get_month_names(width, context, self.locale)[self.value.month] |
794 | |
215
d37628e752c4
Dummy/stub implementation for week-in-year and week-in-month date format fields. Also, treat extended year the same as the regular year field, not even ICU seems to handle it specially.
cmlenz
parents:
129
diff
changeset
|
795 def format_week(self, char, num): |
239 | 796 if char.islower(): # week of year |
242
059b74719f6b
Finish implementation of day-of-year and day-of-month for now, and fix implementation of year-of-week-of-year field. Closes #46. I suspect there are still cases not entirely covered by this implementation, but those can be filed as separate tickets.
cmlenz
parents:
241
diff
changeset
|
797 day_of_year = self.get_day_of_year() |
059b74719f6b
Finish implementation of day-of-year and day-of-month for now, and fix implementation of year-of-week-of-year field. Closes #46. I suspect there are still cases not entirely covered by this implementation, but those can be filed as separate tickets.
cmlenz
parents:
241
diff
changeset
|
798 week = self.get_week_number(day_of_year) |
240 | 799 if week == 0: |
242
059b74719f6b
Finish implementation of day-of-year and day-of-month for now, and fix implementation of year-of-week-of-year field. Closes #46. I suspect there are still cases not entirely covered by this implementation, but those can be filed as separate tickets.
cmlenz
parents:
241
diff
changeset
|
800 date = self.value - timedelta(days=day_of_year) |
059b74719f6b
Finish implementation of day-of-year and day-of-month for now, and fix implementation of year-of-week-of-year field. Closes #46. I suspect there are still cases not entirely covered by this implementation, but those can be filed as separate tickets.
cmlenz
parents:
241
diff
changeset
|
801 week = self.get_week_number(self.get_day_of_year(date), |
059b74719f6b
Finish implementation of day-of-year and day-of-month for now, and fix implementation of year-of-week-of-year field. Closes #46. I suspect there are still cases not entirely covered by this implementation, but those can be filed as separate tickets.
cmlenz
parents:
241
diff
changeset
|
802 date.weekday()) |
240 | 803 return self.format(week, num) |
239 | 804 else: # week of month |
240 | 805 week = self.get_week_number(self.value.day) |
806 if week == 0: | |
242
059b74719f6b
Finish implementation of day-of-year and day-of-month for now, and fix implementation of year-of-week-of-year field. Closes #46. I suspect there are still cases not entirely covered by this implementation, but those can be filed as separate tickets.
cmlenz
parents:
241
diff
changeset
|
807 date = self.value - timedelta(days=self.value.day) |
059b74719f6b
Finish implementation of day-of-year and day-of-month for now, and fix implementation of year-of-week-of-year field. Closes #46. I suspect there are still cases not entirely covered by this implementation, but those can be filed as separate tickets.
cmlenz
parents:
241
diff
changeset
|
808 week = self.get_week_number(date.day, date.weekday()) |
240 | 809 pass |
810 return '%d' % week | |
215
d37628e752c4
Dummy/stub implementation for week-in-year and week-in-month date format fields. Also, treat extended year the same as the regular year field, not even ICU seems to handle it specially.
cmlenz
parents:
129
diff
changeset
|
811 |
15 | 812 def format_weekday(self, char, num): |
813 if num < 3: | |
814 if char.islower(): | |
815 value = 7 - self.locale.first_week_day + self.value.weekday() | |
816 return self.format(value % 7 + 1, num) | |
817 num = 3 | |
818 weekday = self.value.weekday() | |
819 width = {3: 'abbreviated', 4: 'wide', 5: 'narrow'}[num] | |
820 context = {3: 'format', 4: 'format', 5: 'stand-alone'}[num] | |
1 | 821 return get_day_names(width, context, self.locale)[weekday] |
822 | |
221
898b9450f274
Implement day-of-year date format field. Closes #49.
cmlenz
parents:
217
diff
changeset
|
823 def format_day_of_year(self, num): |
239 | 824 return self.format(self.get_day_of_year(), num) |
221
898b9450f274
Implement day-of-year date format field. Closes #49.
cmlenz
parents:
217
diff
changeset
|
825 |
241
9fedbb6f9871
Implement day-of-week-in-month field in date formatting. Closes #50.
cmlenz
parents:
240
diff
changeset
|
826 def format_day_of_week_in_month(self): |
9fedbb6f9871
Implement day-of-week-in-month field in date formatting. Closes #50.
cmlenz
parents:
240
diff
changeset
|
827 return '%d' % ((self.value.day - 1) / 7 + 1) |
9fedbb6f9871
Implement day-of-week-in-month field in date formatting. Closes #50.
cmlenz
parents:
240
diff
changeset
|
828 |
15 | 829 def format_period(self, char): |
276 | 830 period = {0: 'am', 1: 'pm'}[int(self.value.hour >= 12)] |
1 | 831 return get_period_names(locale=self.locale)[period] |
832 | |
217 | 833 def format_frac_seconds(self, num): |
216
1f3c3924b1b5
Support for fractional seconds field in date formatting. Closes #47.
cmlenz
parents:
215
diff
changeset
|
834 value = str(self.value.microsecond) |
1f3c3924b1b5
Support for fractional seconds field in date formatting. Closes #47.
cmlenz
parents:
215
diff
changeset
|
835 return self.format(round(float('.%s' % value), num) * 10**num, num) |
1f3c3924b1b5
Support for fractional seconds field in date formatting. Closes #47.
cmlenz
parents:
215
diff
changeset
|
836 |
217 | 837 def format_milliseconds_in_day(self, num): |
838 msecs = self.value.microsecond // 1000 + self.value.second * 1000 + \ | |
839 self.value.minute * 60000 + self.value.hour * 3600000 | |
840 return self.format(msecs, num) | |
841 | |
29 | 842 def format_timezone(self, char, num): |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
843 width = {3: 'short', 4: 'long'}[max(3, num)] |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
844 if char == 'z': |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
845 return get_timezone_name(self.value, width, locale=self.locale) |
29 | 846 elif char == 'Z': |
247
f3fbecf951b0
`get_timezone_gmt()` wasn't getting the locale passed in all cases, which led to test errors when the default locale wasn't configured via environment variables.
cmlenz
parents:
242
diff
changeset
|
847 return get_timezone_gmt(self.value, width, locale=self.locale) |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
848 elif char == 'v': |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
849 return get_timezone_name(self.value.tzinfo, width, |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
850 locale=self.locale) |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
851 elif char == 'V': |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
852 if num == 1: |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
853 return get_timezone_name(self.value.tzinfo, width, |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
854 uncommon=True, locale=self.locale) |
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
855 return get_timezone_location(self.value.tzinfo, locale=self.locale) |
29 | 856 |
1 | 857 def format(self, value, length): |
858 return ('%%0%dd' % length) % value | |
859 | |
242
059b74719f6b
Finish implementation of day-of-year and day-of-month for now, and fix implementation of year-of-week-of-year field. Closes #46. I suspect there are still cases not entirely covered by this implementation, but those can be filed as separate tickets.
cmlenz
parents:
241
diff
changeset
|
860 def get_day_of_year(self, date=None): |
059b74719f6b
Finish implementation of day-of-year and day-of-month for now, and fix implementation of year-of-week-of-year field. Closes #46. I suspect there are still cases not entirely covered by this implementation, but those can be filed as separate tickets.
cmlenz
parents:
241
diff
changeset
|
861 if date is None: |
059b74719f6b
Finish implementation of day-of-year and day-of-month for now, and fix implementation of year-of-week-of-year field. Closes #46. I suspect there are still cases not entirely covered by this implementation, but those can be filed as separate tickets.
cmlenz
parents:
241
diff
changeset
|
862 date = self.value |
059b74719f6b
Finish implementation of day-of-year and day-of-month for now, and fix implementation of year-of-week-of-year field. Closes #46. I suspect there are still cases not entirely covered by this implementation, but those can be filed as separate tickets.
cmlenz
parents:
241
diff
changeset
|
863 return (date - date_(date.year, 1, 1)).days + 1 |
239 | 864 |
242
059b74719f6b
Finish implementation of day-of-year and day-of-month for now, and fix implementation of year-of-week-of-year field. Closes #46. I suspect there are still cases not entirely covered by this implementation, but those can be filed as separate tickets.
cmlenz
parents:
241
diff
changeset
|
865 def get_week_number(self, day_of_period, day_of_week=None): |
239 | 866 """Return the number of the week of a day within a period. This may be |
867 the week number in a year or the week number in a month. | |
868 | |
869 Usually this will return a value equal to or greater than 1, but if the | |
870 first week of the period is so short that it actually counts as the last | |
871 week of the previous period, this function will return 0. | |
872 | |
873 >>> format = DateTimeFormat(date(2006, 1, 8), Locale.parse('de_DE')) | |
874 >>> format.get_week_number(6) | |
875 1 | |
876 | |
877 >>> format = DateTimeFormat(date(2006, 1, 8), Locale.parse('en_US')) | |
878 >>> format.get_week_number(6) | |
879 2 | |
880 | |
881 :param day_of_period: the number of the day in the period (usually | |
882 either the day of month or the day of year) | |
242
059b74719f6b
Finish implementation of day-of-year and day-of-month for now, and fix implementation of year-of-week-of-year field. Closes #46. I suspect there are still cases not entirely covered by this implementation, but those can be filed as separate tickets.
cmlenz
parents:
241
diff
changeset
|
883 :param day_of_week: the week day; if ommitted, the week day of the |
059b74719f6b
Finish implementation of day-of-year and day-of-month for now, and fix implementation of year-of-week-of-year field. Closes #46. I suspect there are still cases not entirely covered by this implementation, but those can be filed as separate tickets.
cmlenz
parents:
241
diff
changeset
|
884 current date is assumed |
239 | 885 """ |
242
059b74719f6b
Finish implementation of day-of-year and day-of-month for now, and fix implementation of year-of-week-of-year field. Closes #46. I suspect there are still cases not entirely covered by this implementation, but those can be filed as separate tickets.
cmlenz
parents:
241
diff
changeset
|
886 if day_of_week is None: |
059b74719f6b
Finish implementation of day-of-year and day-of-month for now, and fix implementation of year-of-week-of-year field. Closes #46. I suspect there are still cases not entirely covered by this implementation, but those can be filed as separate tickets.
cmlenz
parents:
241
diff
changeset
|
887 day_of_week = self.value.weekday() |
059b74719f6b
Finish implementation of day-of-year and day-of-month for now, and fix implementation of year-of-week-of-year field. Closes #46. I suspect there are still cases not entirely covered by this implementation, but those can be filed as separate tickets.
cmlenz
parents:
241
diff
changeset
|
888 first_day = (day_of_week - self.locale.first_week_day - |
239 | 889 day_of_period + 1) % 7 |
890 if first_day < 0: | |
891 first_day += 7 | |
892 week_number = (day_of_period + first_day - 1) / 7 | |
893 if 7 - first_day >= self.locale.min_week_days: | |
894 week_number += 1 | |
895 return week_number | |
896 | |
1 | 897 |
898 PATTERN_CHARS = { | |
15 | 899 'G': [1, 2, 3, 4, 5], # era |
900 'y': None, 'Y': None, 'u': None, # year | |
901 'Q': [1, 2, 3, 4], 'q': [1, 2, 3, 4], # quarter | |
902 'M': [1, 2, 3, 4, 5], 'L': [1, 2, 3, 4, 5], # month | |
903 'w': [1, 2], 'W': [1], # week | |
904 'd': [1, 2], 'D': [1, 2, 3], 'F': [1], 'g': None, # day | |
905 'E': [1, 2, 3, 4, 5], 'e': [1, 2, 3, 4, 5], 'c': [1, 3, 4, 5], # week day | |
906 'a': [1], # period | |
907 'h': [1, 2], 'H': [1, 2], 'K': [1, 2], 'k': [1, 2], # hour | |
908 'm': [1, 2], # minute | |
909 's': [1, 2], 'S': None, 'A': None, # second | |
233
bc22f5aef216
Upgraded to CLDR 1.5 and improved timezone formatting.
cmlenz
parents:
221
diff
changeset
|
910 'z': [1, 2, 3, 4], 'Z': [1, 2, 3, 4], 'v': [1, 4], 'V': [1, 4] # zone |
1 | 911 } |
912 | |
913 def parse_pattern(pattern): | |
914 """Parse date, time, and datetime format patterns. | |
915 | |
916 >>> parse_pattern("MMMMd").format | |
917 u'%(MMMM)s%(d)s' | |
918 >>> parse_pattern("MMM d, yyyy").format | |
919 u'%(MMM)s %(d)s, %(yyyy)s' | |
16 | 920 |
921 Pattern can contain literal strings in single quotes: | |
922 | |
1 | 923 >>> parse_pattern("H:mm' Uhr 'z").format |
924 u'%(H)s:%(mm)s Uhr %(z)s' | |
925 | |
16 | 926 An actual single quote can be used by using two adjacent single quote |
927 characters: | |
928 | |
929 >>> parse_pattern("hh' o''clock'").format | |
930 u"%(hh)s o'clock" | |
931 | |
1 | 932 :param pattern: the formatting pattern to parse |
933 """ | |
12
a2c54ef107c2
* Removed pkg_resources/setuptools requirement from various places.
cmlenz
parents:
8
diff
changeset
|
934 if type(pattern) is DateTimePattern: |
1 | 935 return pattern |
936 | |
937 result = [] | |
938 quotebuf = None | |
939 charbuf = [] | |
940 fieldchar = [''] | |
941 fieldnum = [0] | |
942 | |
943 def append_chars(): | |
944 result.append(''.join(charbuf).replace('%', '%%')) | |
945 del charbuf[:] | |
946 | |
947 def append_field(): | |
948 limit = PATTERN_CHARS[fieldchar[0]] | |
15 | 949 if limit and fieldnum[0] not in limit: |
1 | 950 raise ValueError('Invalid length for field: %r' |
951 % (fieldchar[0] * fieldnum[0])) | |
952 result.append('%%(%s)s' % (fieldchar[0] * fieldnum[0])) | |
953 fieldchar[0] = '' | |
954 fieldnum[0] = 0 | |
955 | |
16 | 956 for idx, char in enumerate(pattern.replace("''", '\0')): |
1 | 957 if quotebuf is None: |
958 if char == "'": # quote started | |
959 if fieldchar[0]: | |
960 append_field() | |
961 elif charbuf: | |
962 append_chars() | |
963 quotebuf = [] | |
964 elif char in PATTERN_CHARS: | |
965 if charbuf: | |
966 append_chars() | |
967 if char == fieldchar[0]: | |
968 fieldnum[0] += 1 | |
969 else: | |
970 if fieldchar[0]: | |
971 append_field() | |
972 fieldchar[0] = char | |
973 fieldnum[0] = 1 | |
974 else: | |
975 if fieldchar[0]: | |
976 append_field() | |
977 charbuf.append(char) | |
978 | |
979 elif quotebuf is not None: | |
16 | 980 if char == "'": # end of quote |
1 | 981 charbuf.extend(quotebuf) |
982 quotebuf = None | |
983 else: # inside quote | |
984 quotebuf.append(char) | |
985 | |
986 if fieldchar[0]: | |
987 append_field() | |
988 elif charbuf: | |
989 append_chars() | |
990 | |
16 | 991 return DateTimePattern(pattern, u''.join(result).replace('\0', "'")) |