web/lib/django/utils/dateformat.py
changeset 0 0d40e90630ef
child 29 cc9b7e14412b
equal deleted inserted replaced
-1:000000000000 0:0d40e90630ef
       
     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'(?<!\\)([aAbBdDfFgGhHiIjlLmMnNOPrsStTUwWyYzZ])')
       
    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 class DateFormat(TimeFormat):
       
   108     year_days = [None, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
       
   109 
       
   110     def __init__(self, dt):
       
   111         # Accepts either a datetime or date object.
       
   112         self.data = dt
       
   113         self.timezone = getattr(dt, 'tzinfo', None)
       
   114         if hasattr(self.data, 'hour') and not self.timezone:
       
   115             self.timezone = LocalTimezone(dt)
       
   116 
       
   117     def b(self):
       
   118         "Month, textual, 3 letters, lowercase; e.g. 'jan'"
       
   119         return MONTHS_3[self.data.month]
       
   120 
       
   121     def d(self):
       
   122         "Day of the month, 2 digits with leading zeros; i.e. '01' to '31'"
       
   123         return u'%02d' % self.data.day
       
   124 
       
   125     def D(self):
       
   126         "Day of the week, textual, 3 letters; e.g. 'Fri'"
       
   127         return WEEKDAYS_ABBR[self.data.weekday()]
       
   128 
       
   129     def F(self):
       
   130         "Month, textual, long; e.g. 'January'"
       
   131         return MONTHS[self.data.month]
       
   132 
       
   133     def I(self):
       
   134         "'1' if Daylight Savings Time, '0' otherwise."
       
   135         if self.timezone and self.timezone.dst(self.data):
       
   136             return u'1'
       
   137         else:
       
   138             return u'0'
       
   139 
       
   140     def j(self):
       
   141         "Day of the month without leading zeros; i.e. '1' to '31'"
       
   142         return self.data.day
       
   143 
       
   144     def l(self):
       
   145         "Day of the week, textual, long; e.g. 'Friday'"
       
   146         return WEEKDAYS[self.data.weekday()]
       
   147 
       
   148     def L(self):
       
   149         "Boolean for whether it is a leap year; i.e. True or False"
       
   150         return calendar.isleap(self.data.year)
       
   151 
       
   152     def m(self):
       
   153         "Month; i.e. '01' to '12'"
       
   154         return u'%02d' % self.data.month
       
   155 
       
   156     def M(self):
       
   157         "Month, textual, 3 letters; e.g. 'Jan'"
       
   158         return MONTHS_3[self.data.month].title()
       
   159 
       
   160     def n(self):
       
   161         "Month without leading zeros; i.e. '1' to '12'"
       
   162         return self.data.month
       
   163 
       
   164     def N(self):
       
   165         "Month abbreviation in Associated Press style. Proprietary extension."
       
   166         return MONTHS_AP[self.data.month]
       
   167 
       
   168     def O(self):
       
   169         "Difference to Greenwich time in hours; e.g. '+0200'"
       
   170         seconds = self.Z()
       
   171         return u"%+03d%02d" % (seconds // 3600, (seconds // 60) % 60)
       
   172 
       
   173     def r(self):
       
   174         "RFC 2822 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'"
       
   175         return self.format('D, j M Y H:i:s O')
       
   176 
       
   177     def S(self):
       
   178         "English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th'"
       
   179         if self.data.day in (11, 12, 13): # Special case
       
   180             return u'th'
       
   181         last = self.data.day % 10
       
   182         if last == 1:
       
   183             return u'st'
       
   184         if last == 2:
       
   185             return u'nd'
       
   186         if last == 3:
       
   187             return u'rd'
       
   188         return u'th'
       
   189 
       
   190     def t(self):
       
   191         "Number of days in the given month; i.e. '28' to '31'"
       
   192         return u'%02d' % calendar.monthrange(self.data.year, self.data.month)[1]
       
   193 
       
   194     def T(self):
       
   195         "Time zone of this machine; e.g. 'EST' or 'MDT'"
       
   196         name = self.timezone and self.timezone.tzname(self.data) or None
       
   197         if name is None:
       
   198             name = self.format('O')
       
   199         return unicode(name)
       
   200 
       
   201     def U(self):
       
   202         "Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)"
       
   203         if getattr(self.data, 'tzinfo', None):
       
   204             return int(calendar.timegm(self.data.utctimetuple()))
       
   205         else:
       
   206             return int(time.mktime(self.data.timetuple()))
       
   207 
       
   208     def w(self):
       
   209         "Day of the week, numeric, i.e. '0' (Sunday) to '6' (Saturday)"
       
   210         return (self.data.weekday() + 1) % 7
       
   211 
       
   212     def W(self):
       
   213         "ISO-8601 week number of year, weeks starting on Monday"
       
   214         # Algorithm from http://www.personal.ecu.edu/mccartyr/ISOwdALG.txt
       
   215         week_number = None
       
   216         jan1_weekday = self.data.replace(month=1, day=1).weekday() + 1
       
   217         weekday = self.data.weekday() + 1
       
   218         day_of_year = self.z()
       
   219         if day_of_year <= (8 - jan1_weekday) and jan1_weekday > 4:
       
   220             if jan1_weekday == 5 or (jan1_weekday == 6 and calendar.isleap(self.data.year-1)):
       
   221                 week_number = 53
       
   222             else:
       
   223                 week_number = 52
       
   224         else:
       
   225             if calendar.isleap(self.data.year):
       
   226                 i = 366
       
   227             else:
       
   228                 i = 365
       
   229             if (i - day_of_year) < (4 - weekday):
       
   230                 week_number = 1
       
   231             else:
       
   232                 j = day_of_year + (7 - weekday) + (jan1_weekday - 1)
       
   233                 week_number = j // 7
       
   234                 if jan1_weekday > 4:
       
   235                     week_number -= 1
       
   236         return week_number
       
   237 
       
   238     def y(self):
       
   239         "Year, 2 digits; e.g. '99'"
       
   240         return unicode(self.data.year)[2:]
       
   241 
       
   242     def Y(self):
       
   243         "Year, 4 digits; e.g. '1999'"
       
   244         return self.data.year
       
   245 
       
   246     def z(self):
       
   247         "Day of the year; i.e. '0' to '365'"
       
   248         doy = self.year_days[self.data.month] + self.data.day
       
   249         if self.L() and self.data.month > 2:
       
   250             doy += 1
       
   251         return doy
       
   252 
       
   253     def Z(self):
       
   254         """
       
   255         Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for
       
   256         timezones west of UTC is always negative, and for those east of UTC is
       
   257         always positive.
       
   258         """
       
   259         if not self.timezone:
       
   260             return 0
       
   261         offset = self.timezone.utcoffset(self.data)
       
   262         # Only days can be negative, so negative offsets have days=-1 and
       
   263         # seconds positive. Positive offsets have days=0
       
   264         return offset.days * 86400 + offset.seconds
       
   265 
       
   266 def format(value, format_string):
       
   267     "Convenience function"
       
   268     df = DateFormat(value)
       
   269     return df.format(format_string)
       
   270 
       
   271 def time_format(value, format_string):
       
   272     "Convenience function"
       
   273     tf = TimeFormat(value)
       
   274     return tf.format(format_string)