annotate babel/dates.py @ 350:e5db561bf70e

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