You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dateformat.py 11 KiB

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