web/lib/django/utils/dateformat.py
changeset 38 77b6da96e6f1
equal deleted inserted replaced
37:8d941af65caf 38:77b6da96e6f1
       
     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 from django.utils.dates import MONTHS, MONTHS_3, MONTHS_AP, WEEKDAYS, WEEKDAYS_ABBR
       
    18 from django.utils.tzinfo import LocalTimezone
       
    19 from django.utils.translation import ugettext as _
       
    20 from django.utils.encoding import force_unicode
       
    21 
       
    22 re_formatchars = re.compile(r'(?<!\\)([aAbBcdDfFgGhHiIjlLmMnNOPrsStTUuwWyYzZ])')
       
    23 re_escaped = re.compile(r'\\(.)')
       
    24 
       
    25 class Formatter(object):
       
    26     def format(self, formatstr):
       
    27         pieces = []
       
    28         for i, piece in enumerate(re_formatchars.split(force_unicode(formatstr))):
       
    29             if i % 2:
       
    30                 pieces.append(force_unicode(getattr(self, piece)()))
       
    31             elif piece:
       
    32                 pieces.append(re_escaped.sub(r'\1', piece))
       
    33         return u''.join(pieces)
       
    34 
       
    35 class TimeFormat(Formatter):
       
    36     def __init__(self, t):
       
    37         self.data = t
       
    38 
       
    39     def a(self):
       
    40         "'a.m.' or 'p.m.'"
       
    41         if self.data.hour > 11:
       
    42             return _('p.m.')
       
    43         return _('a.m.')
       
    44 
       
    45     def A(self):
       
    46         "'AM' or 'PM'"
       
    47         if self.data.hour > 11:
       
    48             return _('PM')
       
    49         return _('AM')
       
    50 
       
    51     def B(self):
       
    52         "Swatch Internet time"
       
    53         raise NotImplementedError
       
    54 
       
    55     def f(self):
       
    56         """
       
    57         Time, in 12-hour hours and minutes, with minutes left off if they're
       
    58         zero.
       
    59         Examples: '1', '1:30', '2:05', '2'
       
    60         Proprietary extension.
       
    61         """
       
    62         if self.data.minute == 0:
       
    63             return self.g()
       
    64         return u'%s:%s' % (self.g(), self.i())
       
    65 
       
    66     def g(self):
       
    67         "Hour, 12-hour format without leading zeros; i.e. '1' to '12'"
       
    68         if self.data.hour == 0:
       
    69             return 12
       
    70         if self.data.hour > 12:
       
    71             return self.data.hour - 12
       
    72         return self.data.hour
       
    73 
       
    74     def G(self):
       
    75         "Hour, 24-hour format without leading zeros; i.e. '0' to '23'"
       
    76         return self.data.hour
       
    77 
       
    78     def h(self):
       
    79         "Hour, 12-hour format; i.e. '01' to '12'"
       
    80         return u'%02d' % self.g()
       
    81 
       
    82     def H(self):
       
    83         "Hour, 24-hour format; i.e. '00' to '23'"
       
    84         return u'%02d' % self.G()
       
    85 
       
    86     def i(self):
       
    87         "Minutes; i.e. '00' to '59'"
       
    88         return u'%02d' % self.data.minute
       
    89 
       
    90     def P(self):
       
    91         """
       
    92         Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off
       
    93         if they're zero and the strings 'midnight' and 'noon' if appropriate.
       
    94         Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.'
       
    95         Proprietary extension.
       
    96         """
       
    97         if self.data.minute == 0 and self.data.hour == 0:
       
    98             return _('midnight')
       
    99         if self.data.minute == 0 and self.data.hour == 12:
       
   100             return _('noon')
       
   101         return u'%s %s' % (self.f(), self.a())
       
   102 
       
   103     def s(self):
       
   104         "Seconds; i.e. '00' to '59'"
       
   105         return u'%02d' % self.data.second
       
   106 
       
   107     def u(self):
       
   108         "Microseconds"
       
   109         return self.data.microsecond
       
   110 
       
   111 
       
   112 class DateFormat(TimeFormat):
       
   113     year_days = [None, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
       
   114 
       
   115     def __init__(self, dt):
       
   116         # Accepts either a datetime or date object.
       
   117         self.data = dt
       
   118         self.timezone = getattr(dt, 'tzinfo', None)
       
   119         if hasattr(self.data, 'hour') and not self.timezone:
       
   120             self.timezone = LocalTimezone(dt)
       
   121 
       
   122     def b(self):
       
   123         "Month, textual, 3 letters, lowercase; e.g. 'jan'"
       
   124         return MONTHS_3[self.data.month]
       
   125 
       
   126     def c(self):
       
   127         """
       
   128         ISO 8601 Format
       
   129         Example : '2008-01-02T10:30:00.000123'
       
   130         """
       
   131         return self.data.isoformat()
       
   132 
       
   133     def d(self):
       
   134         "Day of the month, 2 digits with leading zeros; i.e. '01' to '31'"
       
   135         return u'%02d' % self.data.day
       
   136 
       
   137     def D(self):
       
   138         "Day of the week, textual, 3 letters; e.g. 'Fri'"
       
   139         return WEEKDAYS_ABBR[self.data.weekday()]
       
   140 
       
   141     def F(self):
       
   142         "Month, textual, long; e.g. 'January'"
       
   143         return MONTHS[self.data.month]
       
   144 
       
   145     def I(self):
       
   146         "'1' if Daylight Savings Time, '0' otherwise."
       
   147         if self.timezone and self.timezone.dst(self.data):
       
   148             return u'1'
       
   149         else:
       
   150             return u'0'
       
   151 
       
   152     def j(self):
       
   153         "Day of the month without leading zeros; i.e. '1' to '31'"
       
   154         return self.data.day
       
   155 
       
   156     def l(self):
       
   157         "Day of the week, textual, long; e.g. 'Friday'"
       
   158         return WEEKDAYS[self.data.weekday()]
       
   159 
       
   160     def L(self):
       
   161         "Boolean for whether it is a leap year; i.e. True or False"
       
   162         return calendar.isleap(self.data.year)
       
   163 
       
   164     def m(self):
       
   165         "Month; i.e. '01' to '12'"
       
   166         return u'%02d' % self.data.month
       
   167 
       
   168     def M(self):
       
   169         "Month, textual, 3 letters; e.g. 'Jan'"
       
   170         return MONTHS_3[self.data.month].title()
       
   171 
       
   172     def n(self):
       
   173         "Month without leading zeros; i.e. '1' to '12'"
       
   174         return self.data.month
       
   175 
       
   176     def N(self):
       
   177         "Month abbreviation in Associated Press style. Proprietary extension."
       
   178         return MONTHS_AP[self.data.month]
       
   179 
       
   180     def O(self):
       
   181         "Difference to Greenwich time in hours; e.g. '+0200'"
       
   182         seconds = self.Z()
       
   183         return u"%+03d%02d" % (seconds // 3600, (seconds // 60) % 60)
       
   184 
       
   185     def r(self):
       
   186         "RFC 2822 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'"
       
   187         return self.format('D, j M Y H:i:s O')
       
   188 
       
   189     def S(self):
       
   190         "English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th'"
       
   191         if self.data.day in (11, 12, 13): # Special case
       
   192             return u'th'
       
   193         last = self.data.day % 10
       
   194         if last == 1:
       
   195             return u'st'
       
   196         if last == 2:
       
   197             return u'nd'
       
   198         if last == 3:
       
   199             return u'rd'
       
   200         return u'th'
       
   201 
       
   202     def t(self):
       
   203         "Number of days in the given month; i.e. '28' to '31'"
       
   204         return u'%02d' % calendar.monthrange(self.data.year, self.data.month)[1]
       
   205 
       
   206     def T(self):
       
   207         "Time zone of this machine; e.g. 'EST' or 'MDT'"
       
   208         name = self.timezone and self.timezone.tzname(self.data) or None
       
   209         if name is None:
       
   210             name = self.format('O')
       
   211         return unicode(name)
       
   212 
       
   213     def U(self):
       
   214         "Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)"
       
   215         if getattr(self.data, 'tzinfo', None):
       
   216             return int(calendar.timegm(self.data.utctimetuple()))
       
   217         else:
       
   218             return int(time.mktime(self.data.timetuple()))
       
   219 
       
   220     def w(self):
       
   221         "Day of the week, numeric, i.e. '0' (Sunday) to '6' (Saturday)"
       
   222         return (self.data.weekday() + 1) % 7
       
   223 
       
   224     def W(self):
       
   225         "ISO-8601 week number of year, weeks starting on Monday"
       
   226         # Algorithm from http://www.personal.ecu.edu/mccartyr/ISOwdALG.txt
       
   227         week_number = None
       
   228         jan1_weekday = self.data.replace(month=1, day=1).weekday() + 1
       
   229         weekday = self.data.weekday() + 1
       
   230         day_of_year = self.z()
       
   231         if day_of_year <= (8 - jan1_weekday) and jan1_weekday > 4:
       
   232             if jan1_weekday == 5 or (jan1_weekday == 6 and calendar.isleap(self.data.year-1)):
       
   233                 week_number = 53
       
   234             else:
       
   235                 week_number = 52
       
   236         else:
       
   237             if calendar.isleap(self.data.year):
       
   238                 i = 366
       
   239             else:
       
   240                 i = 365
       
   241             if (i - day_of_year) < (4 - weekday):
       
   242                 week_number = 1
       
   243             else:
       
   244                 j = day_of_year + (7 - weekday) + (jan1_weekday - 1)
       
   245                 week_number = j // 7
       
   246                 if jan1_weekday > 4:
       
   247                     week_number -= 1
       
   248         return week_number
       
   249 
       
   250     def y(self):
       
   251         "Year, 2 digits; e.g. '99'"
       
   252         return unicode(self.data.year)[2:]
       
   253 
       
   254     def Y(self):
       
   255         "Year, 4 digits; e.g. '1999'"
       
   256         return self.data.year
       
   257 
       
   258     def z(self):
       
   259         "Day of the year; i.e. '0' to '365'"
       
   260         doy = self.year_days[self.data.month] + self.data.day
       
   261         if self.L() and self.data.month > 2:
       
   262             doy += 1
       
   263         return doy
       
   264 
       
   265     def Z(self):
       
   266         """
       
   267         Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for
       
   268         timezones west of UTC is always negative, and for those east of UTC is
       
   269         always positive.
       
   270         """
       
   271         if not self.timezone:
       
   272             return 0
       
   273         offset = self.timezone.utcoffset(self.data)
       
   274         # Only days can be negative, so negative offsets have days=-1 and
       
   275         # seconds positive. Positive offsets have days=0
       
   276         return offset.days * 86400 + offset.seconds
       
   277 
       
   278 def format(value, format_string):
       
   279     "Convenience function"
       
   280     df = DateFormat(value)
       
   281     return df.format(format_string)
       
   282 
       
   283 def time_format(value, format_string):
       
   284     "Convenience function"
       
   285     tf = TimeFormat(value)
       
   286     return tf.format(format_string)