PageRenderTime 43ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/django/branches/0.95-bugfixes/django/utils/dateformat.py

https://bitbucket.org/mirror/django/
Python | 257 lines | 244 code | 0 blank | 13 comment | 3 complexity | aff32d75e86e5ece31e4554f22fa54cf MD5 | raw file
Possible License(s): BSD-3-Clause
  1. """
  2. PHP date() style date formatting
  3. See http://www.php.net/date for format strings
  4. Usage:
  5. >>> import datetime
  6. >>> d = datetime.datetime.now()
  7. >>> df = DateFormat(d)
  8. >>> print df.format('jS F Y H:i')
  9. 7th October 2003 11:39
  10. >>>
  11. """
  12. from django.utils.dates import MONTHS, MONTHS_AP, WEEKDAYS
  13. from django.utils.tzinfo import LocalTimezone
  14. from calendar import isleap, monthrange
  15. import re, time
  16. re_formatchars = re.compile(r'(?<!\\)([aABdDfFgGhHiIjlLmMnNOPrsStTUwWyYzZ])')
  17. re_escaped = re.compile(r'\\(.)')
  18. class Formatter(object):
  19. def format(self, formatstr):
  20. pieces = []
  21. for i, piece in enumerate(re_formatchars.split(formatstr)):
  22. if i % 2:
  23. pieces.append(str(getattr(self, piece)()))
  24. elif piece:
  25. pieces.append(re_escaped.sub(r'\1', piece))
  26. return ''.join(pieces)
  27. class TimeFormat(Formatter):
  28. def __init__(self, t):
  29. self.data = t
  30. def a(self):
  31. "'a.m.' or 'p.m.'"
  32. if self.data.hour > 11:
  33. return 'p.m.'
  34. return 'a.m.'
  35. def A(self):
  36. "'AM' or 'PM'"
  37. if self.data.hour > 11:
  38. return 'PM'
  39. return 'AM'
  40. def B(self):
  41. "Swatch Internet time"
  42. raise NotImplementedError
  43. def f(self):
  44. """
  45. Time, in 12-hour hours and minutes, with minutes left off if they're zero.
  46. Examples: '1', '1:30', '2:05', '2'
  47. Proprietary extension.
  48. """
  49. if self.data.minute == 0:
  50. return self.g()
  51. return '%s:%s' % (self.g(), self.i())
  52. def g(self):
  53. "Hour, 12-hour format without leading zeros; i.e. '1' to '12'"
  54. if self.data.hour == 0:
  55. return 12
  56. if self.data.hour > 12:
  57. return self.data.hour - 12
  58. return self.data.hour
  59. def G(self):
  60. "Hour, 24-hour format without leading zeros; i.e. '0' to '23'"
  61. return self.data.hour
  62. def h(self):
  63. "Hour, 12-hour format; i.e. '01' to '12'"
  64. return '%02d' % self.g()
  65. def H(self):
  66. "Hour, 24-hour format; i.e. '00' to '23'"
  67. return '%02d' % self.G()
  68. def i(self):
  69. "Minutes; i.e. '00' to '59'"
  70. return '%02d' % self.data.minute
  71. def P(self):
  72. """
  73. Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off
  74. if they're zero and the strings 'midnight' and 'noon' if appropriate.
  75. Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.'
  76. Proprietary extension.
  77. """
  78. if self.data.minute == 0 and self.data.hour == 0:
  79. return 'midnight'
  80. if self.data.minute == 0 and self.data.hour == 12:
  81. return 'noon'
  82. return '%s %s' % (self.f(), self.a())
  83. def s(self):
  84. "Seconds; i.e. '00' to '59'"
  85. return '%02d' % self.data.second
  86. class DateFormat(TimeFormat):
  87. year_days = [None, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
  88. def __init__(self, dt):
  89. # Accepts either a datetime or date object.
  90. self.data = dt
  91. self.timezone = getattr(dt, 'tzinfo', None)
  92. if hasattr(self.data, 'hour') and not self.timezone:
  93. self.timezone = LocalTimezone(dt)
  94. def d(self):
  95. "Day of the month, 2 digits with leading zeros; i.e. '01' to '31'"
  96. return '%02d' % self.data.day
  97. def D(self):
  98. "Day of the week, textual, 3 letters; e.g. 'Fri'"
  99. return WEEKDAYS[self.data.weekday()][0:3]
  100. def F(self):
  101. "Month, textual, long; e.g. 'January'"
  102. return MONTHS[self.data.month]
  103. def I(self):
  104. "'1' if Daylight Savings Time, '0' otherwise."
  105. if self.timezone.dst(self.data):
  106. return '1'
  107. else:
  108. return '0'
  109. def j(self):
  110. "Day of the month without leading zeros; i.e. '1' to '31'"
  111. return self.data.day
  112. def l(self):
  113. "Day of the week, textual, long; e.g. 'Friday'"
  114. return WEEKDAYS[self.data.weekday()]
  115. def L(self):
  116. "Boolean for whether it is a leap year; i.e. True or False"
  117. return isleap(self.data.year)
  118. def m(self):
  119. "Month; i.e. '01' to '12'"
  120. return '%02d' % self.data.month
  121. def M(self):
  122. "Month, textual, 3 letters; e.g. 'Jan'"
  123. return MONTHS[self.data.month][0:3]
  124. def n(self):
  125. "Month without leading zeros; i.e. '1' to '12'"
  126. return self.data.month
  127. def N(self):
  128. "Month abbreviation in Associated Press style. Proprietary extension."
  129. return MONTHS_AP[self.data.month]
  130. def O(self):
  131. "Difference to Greenwich time in hours; e.g. '+0200'"
  132. tz = self.timezone.utcoffset(self.data)
  133. return "%+03d%02d" % (tz.seconds // 3600, (tz.seconds // 60) % 60)
  134. def r(self):
  135. "RFC 822 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'"
  136. return self.format('D, j M Y H:i:s O')
  137. def S(self):
  138. "English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th'"
  139. if self.data.day in (11, 12, 13): # Special case
  140. return 'th'
  141. last = self.data.day % 10
  142. if last == 1:
  143. return 'st'
  144. if last == 2:
  145. return 'nd'
  146. if last == 3:
  147. return 'rd'
  148. return 'th'
  149. def t(self):
  150. "Number of days in the given month; i.e. '28' to '31'"
  151. return '%02d' % monthrange(self.data.year, self.data.month)[1]
  152. def T(self):
  153. "Time zone of this machine; e.g. 'EST' or 'MDT'"
  154. name = self.timezone.tzname(self.data)
  155. if name is None:
  156. name = self.format('O')
  157. return name
  158. def U(self):
  159. "Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)"
  160. off = self.timezone.utcoffset(self.data)
  161. return int(time.mktime(self.data.timetuple())) + off.seconds * 60
  162. def w(self):
  163. "Day of the week, numeric, i.e. '0' (Sunday) to '6' (Saturday)"
  164. return (self.data.weekday() + 1) % 7
  165. def W(self):
  166. "ISO-8601 week number of year, weeks starting on Monday"
  167. # Algorithm from http://www.personal.ecu.edu/mccartyr/ISOwdALG.txt
  168. week_number = None
  169. jan1_weekday = self.data.replace(month=1, day=1).weekday() + 1
  170. weekday = self.data.weekday() + 1
  171. day_of_year = self.z()
  172. if day_of_year <= (8 - jan1_weekday) and jan1_weekday > 4:
  173. if jan1_weekday == 5 or (jan1_weekday == 6 and isleap(self.data.year-1)):
  174. week_number = 53
  175. else:
  176. week_number = 52
  177. else:
  178. if isleap(self.data.year):
  179. i = 366
  180. else:
  181. i = 365
  182. if (i - day_of_year) < (4 - weekday):
  183. week_number = 1
  184. else:
  185. j = day_of_year + (7 - weekday) + (jan1_weekday - 1)
  186. week_number = j / 7
  187. if jan1_weekday > 4:
  188. week_number -= 1
  189. return week_number
  190. def y(self):
  191. "Year, 2 digits; e.g. '99'"
  192. return str(self.data.year)[2:]
  193. def Y(self):
  194. "Year, 4 digits; e.g. '1999'"
  195. return self.data.year
  196. def z(self):
  197. "Day of the year; i.e. '0' to '365'"
  198. doy = self.year_days[self.data.month] + self.data.day
  199. if self.L() and self.data.month > 2:
  200. doy += 1
  201. return doy
  202. def Z(self):
  203. """Time zone offset in seconds (i.e. '-43200' to '43200'). The offset
  204. for timezones west of UTC is always negative, and for those east of UTC
  205. is always positive."""
  206. return self.timezone.utcoffset(self.data).seconds
  207. def format(value, format_string):
  208. "Convenience function"
  209. df = DateFormat(value)
  210. return df.format(format_string)
  211. def time_format(value, format_string):
  212. "Convenience function"
  213. tf = TimeFormat(value)
  214. return tf.format(format_string)