Project

General

Profile

Statistics
| Branch: | Revision:

root / env / lib / python2.7 / site-packages / django / utils / dateformat.py @ 1a305335

History | View | Annotate | Download (9.64 KB)

1
"""
2
PHP date() style date formatting
3
See http://www.php.net/date for format strings
4

5
Usage:
6
>>> import datetime
7
>>> d = datetime.datetime.now()
8
>>> df = DateFormat(d)
9
>>> print df.format('jS F Y H:i')
10
7th October 2003 11:39
11
>>>
12
"""
13

    
14
import re
15
import time
16
import calendar
17
import datetime
18

    
19
from django.utils.dates import MONTHS, MONTHS_3, MONTHS_ALT, MONTHS_AP, WEEKDAYS, WEEKDAYS_ABBR
20
from django.utils.tzinfo import LocalTimezone
21
from django.utils.translation import ugettext as _
22
from django.utils.encoding import force_unicode
23
from django.utils.timezone import is_aware, is_naive
24

    
25
re_formatchars = re.compile(r'(?<!\\)([aAbBcdDeEfFgGhHiIjlLmMnNoOPrsStTUuwWyYzZ])')
26
re_escaped = re.compile(r'\\(.)')
27

    
28
class Formatter(object):
29
    def format(self, formatstr):
30
        pieces = []
31
        for i, piece in enumerate(re_formatchars.split(force_unicode(formatstr))):
32
            if i % 2:
33
                pieces.append(force_unicode(getattr(self, piece)()))
34
            elif piece:
35
                pieces.append(re_escaped.sub(r'\1', piece))
36
        return u''.join(pieces)
37

    
38
class TimeFormat(Formatter):
39
    def __init__(self, t):
40
        self.data = t
41

    
42
    def a(self):
43
        "'a.m.' or 'p.m.'"
44
        if self.data.hour > 11:
45
            return _('p.m.')
46
        return _('a.m.')
47

    
48
    def A(self):
49
        "'AM' or 'PM'"
50
        if self.data.hour > 11:
51
            return _('PM')
52
        return _('AM')
53

    
54
    def B(self):
55
        "Swatch Internet time"
56
        raise NotImplementedError
57

    
58
    def f(self):
59
        """
60
        Time, in 12-hour hours and minutes, with minutes left off if they're
61
        zero.
62
        Examples: '1', '1:30', '2:05', '2'
63
        Proprietary extension.
64
        """
65
        if self.data.minute == 0:
66
            return self.g()
67
        return u'%s:%s' % (self.g(), self.i())
68

    
69
    def g(self):
70
        "Hour, 12-hour format without leading zeros; i.e. '1' to '12'"
71
        if self.data.hour == 0:
72
            return 12
73
        if self.data.hour > 12:
74
            return self.data.hour - 12
75
        return self.data.hour
76

    
77
    def G(self):
78
        "Hour, 24-hour format without leading zeros; i.e. '0' to '23'"
79
        return self.data.hour
80

    
81
    def h(self):
82
        "Hour, 12-hour format; i.e. '01' to '12'"
83
        return u'%02d' % self.g()
84

    
85
    def H(self):
86
        "Hour, 24-hour format; i.e. '00' to '23'"
87
        return u'%02d' % self.G()
88

    
89
    def i(self):
90
        "Minutes; i.e. '00' to '59'"
91
        return u'%02d' % self.data.minute
92

    
93
    def P(self):
94
        """
95
        Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off
96
        if they're zero and the strings 'midnight' and 'noon' if appropriate.
97
        Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.'
98
        Proprietary extension.
99
        """
100
        if self.data.minute == 0 and self.data.hour == 0:
101
            return _('midnight')
102
        if self.data.minute == 0 and self.data.hour == 12:
103
            return _('noon')
104
        return u'%s %s' % (self.f(), self.a())
105

    
106
    def s(self):
107
        "Seconds; i.e. '00' to '59'"
108
        return u'%02d' % self.data.second
109

    
110
    def u(self):
111
        "Microseconds"
112
        return self.data.microsecond
113

    
114

    
115
class DateFormat(TimeFormat):
116
    year_days = [None, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
117

    
118
    def __init__(self, dt):
119
        # Accepts either a datetime or date object.
120
        self.data = dt
121
        self.timezone = None
122
        if isinstance(dt, datetime.datetime):
123
            if is_naive(dt):
124
                self.timezone = LocalTimezone(dt)
125
            else:
126
                self.timezone = dt.tzinfo
127

    
128
    def b(self):
129
        "Month, textual, 3 letters, lowercase; e.g. 'jan'"
130
        return MONTHS_3[self.data.month]
131

    
132
    def c(self):
133
        """
134
        ISO 8601 Format
135
        Example : '2008-01-02T10:30:00.000123'
136
        """
137
        return self.data.isoformat()
138

    
139
    def d(self):
140
        "Day of the month, 2 digits with leading zeros; i.e. '01' to '31'"
141
        return u'%02d' % self.data.day
142

    
143
    def D(self):
144
        "Day of the week, textual, 3 letters; e.g. 'Fri'"
145
        return WEEKDAYS_ABBR[self.data.weekday()]
146

    
147
    def e(self):
148
        "Timezone name if available"
149
        try:
150
            if hasattr(self.data, 'tzinfo') and self.data.tzinfo:
151
                # Have to use tzinfo.tzname and not datetime.tzname
152
                # because datatime.tzname does not expect Unicode
153
                return self.data.tzinfo.tzname(self.data) or ""
154
        except NotImplementedError:
155
            pass
156
        return ""
157

    
158
    def E(self):
159
        "Alternative month names as required by some locales. Proprietary extension."
160
        return MONTHS_ALT[self.data.month]
161

    
162
    def F(self):
163
        "Month, textual, long; e.g. 'January'"
164
        return MONTHS[self.data.month]
165

    
166
    def I(self):
167
        "'1' if Daylight Savings Time, '0' otherwise."
168
        if self.timezone and self.timezone.dst(self.data):
169
            return u'1'
170
        else:
171
            return u'0'
172

    
173
    def j(self):
174
        "Day of the month without leading zeros; i.e. '1' to '31'"
175
        return self.data.day
176

    
177
    def l(self):
178
        "Day of the week, textual, long; e.g. 'Friday'"
179
        return WEEKDAYS[self.data.weekday()]
180

    
181
    def L(self):
182
        "Boolean for whether it is a leap year; i.e. True or False"
183
        return calendar.isleap(self.data.year)
184

    
185
    def m(self):
186
        "Month; i.e. '01' to '12'"
187
        return u'%02d' % self.data.month
188

    
189
    def M(self):
190
        "Month, textual, 3 letters; e.g. 'Jan'"
191
        return MONTHS_3[self.data.month].title()
192

    
193
    def n(self):
194
        "Month without leading zeros; i.e. '1' to '12'"
195
        return self.data.month
196

    
197
    def N(self):
198
        "Month abbreviation in Associated Press style. Proprietary extension."
199
        return MONTHS_AP[self.data.month]
200

    
201
    def o(self):
202
        "ISO 8601 year number matching the ISO week number (W)"
203
        return self.data.isocalendar()[0]
204

    
205
    def O(self):
206
        "Difference to Greenwich time in hours; e.g. '+0200', '-0430'"
207
        seconds = self.Z()
208
        sign = '-' if seconds < 0 else '+'
209
        seconds = abs(seconds)
210
        return u"%s%02d%02d" % (sign, seconds // 3600, (seconds // 60) % 60)
211

    
212
    def r(self):
213
        "RFC 2822 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'"
214
        return self.format('D, j M Y H:i:s O')
215

    
216
    def S(self):
217
        "English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th'"
218
        if self.data.day in (11, 12, 13): # Special case
219
            return u'th'
220
        last = self.data.day % 10
221
        if last == 1:
222
            return u'st'
223
        if last == 2:
224
            return u'nd'
225
        if last == 3:
226
            return u'rd'
227
        return u'th'
228

    
229
    def t(self):
230
        "Number of days in the given month; i.e. '28' to '31'"
231
        return u'%02d' % calendar.monthrange(self.data.year, self.data.month)[1]
232

    
233
    def T(self):
234
        "Time zone of this machine; e.g. 'EST' or 'MDT'"
235
        name = self.timezone and self.timezone.tzname(self.data) or None
236
        if name is None:
237
            name = self.format('O')
238
        return unicode(name)
239

    
240
    def U(self):
241
        "Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)"
242
        if isinstance(self.data, datetime.datetime) and is_aware(self.data):
243
            return int(calendar.timegm(self.data.utctimetuple()))
244
        else:
245
            return int(time.mktime(self.data.timetuple()))
246

    
247
    def w(self):
248
        "Day of the week, numeric, i.e. '0' (Sunday) to '6' (Saturday)"
249
        return (self.data.weekday() + 1) % 7
250

    
251
    def W(self):
252
        "ISO-8601 week number of year, weeks starting on Monday"
253
        # Algorithm from http://www.personal.ecu.edu/mccartyr/ISOwdALG.txt
254
        week_number = None
255
        jan1_weekday = self.data.replace(month=1, day=1).weekday() + 1
256
        weekday = self.data.weekday() + 1
257
        day_of_year = self.z()
258
        if day_of_year <= (8 - jan1_weekday) and jan1_weekday > 4:
259
            if jan1_weekday == 5 or (jan1_weekday == 6 and calendar.isleap(self.data.year-1)):
260
                week_number = 53
261
            else:
262
                week_number = 52
263
        else:
264
            if calendar.isleap(self.data.year):
265
                i = 366
266
            else:
267
                i = 365
268
            if (i - day_of_year) < (4 - weekday):
269
                week_number = 1
270
            else:
271
                j = day_of_year + (7 - weekday) + (jan1_weekday - 1)
272
                week_number = j // 7
273
                if jan1_weekday > 4:
274
                    week_number -= 1
275
        return week_number
276

    
277
    def y(self):
278
        "Year, 2 digits; e.g. '99'"
279
        return unicode(self.data.year)[2:]
280

    
281
    def Y(self):
282
        "Year, 4 digits; e.g. '1999'"
283
        return self.data.year
284

    
285
    def z(self):
286
        "Day of the year; i.e. '0' to '365'"
287
        doy = self.year_days[self.data.month] + self.data.day
288
        if self.L() and self.data.month > 2:
289
            doy += 1
290
        return doy
291

    
292
    def Z(self):
293
        """
294
        Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for
295
        timezones west of UTC is always negative, and for those east of UTC is
296
        always positive.
297
        """
298
        if not self.timezone:
299
            return 0
300
        offset = self.timezone.utcoffset(self.data)
301
        # `offset` is a datetime.timedelta. For negative values (to the west of
302
        # UTC) only days can be negative (days=-1) and seconds are always
303
        # positive. e.g. UTC-1 -> timedelta(days=-1, seconds=82800, microseconds=0)
304
        # Positive offsets have days=0
305
        return offset.days * 86400 + offset.seconds
306

    
307
def format(value, format_string):
308
    "Convenience function"
309
    df = DateFormat(value)
310
    return df.format(format_string)
311

    
312
def time_format(value, format_string):
313
    "Convenience function"
314
    tf = TimeFormat(value)
315
    return tf.format(format_string)