dateformat.py 10 KB

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