PageRenderTime 51ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/site-packages/django/utils/dateformat.py

https://gitlab.com/suyesh/Djangotest
Python | 351 lines | 338 code | 0 blank | 13 comment | 3 complexity | 7fccc9522027e3d840fae87977065c5f MD5 | raw file
  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. sign = '-' if seconds < 0 else '+'
  115. seconds = abs(seconds)
  116. return "%s%02d%02d" % (sign, seconds // 3600, (seconds // 60) % 60)
  117. def P(self):
  118. """
  119. Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off
  120. if they're zero and the strings 'midnight' and 'noon' if appropriate.
  121. Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.'
  122. Proprietary extension.
  123. """
  124. if self.data.minute == 0 and self.data.hour == 0:
  125. return _('midnight')
  126. if self.data.minute == 0 and self.data.hour == 12:
  127. return _('noon')
  128. return '%s %s' % (self.f(), self.a())
  129. def s(self):
  130. "Seconds; i.e. '00' to '59'"
  131. return '%02d' % self.data.second
  132. def T(self):
  133. """
  134. Time zone of this machine; e.g. 'EST' or 'MDT'.
  135. If timezone information is not available, this method returns
  136. an empty string.
  137. """
  138. if not self.timezone:
  139. return ""
  140. name = self.timezone.tzname(self.data) if self.timezone else None
  141. if name is None:
  142. name = self.format('O')
  143. return six.text_type(name)
  144. def u(self):
  145. "Microseconds; i.e. '000000' to '999999'"
  146. return '%06d' % self.data.microsecond
  147. def Z(self):
  148. """
  149. Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for
  150. timezones west of UTC is always negative, and for those east of UTC is
  151. always positive.
  152. If timezone information is not available, this method returns
  153. an empty string.
  154. """
  155. if not self.timezone:
  156. return ""
  157. offset = self.timezone.utcoffset(self.data)
  158. # `offset` is a datetime.timedelta. For negative values (to the west of
  159. # UTC) only days can be negative (days=-1) and seconds are always
  160. # positive. e.g. UTC-1 -> timedelta(days=-1, seconds=82800, microseconds=0)
  161. # Positive offsets have days=0
  162. return offset.days * 86400 + offset.seconds
  163. class DateFormat(TimeFormat):
  164. year_days = [None, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
  165. def b(self):
  166. "Month, textual, 3 letters, lowercase; e.g. 'jan'"
  167. return MONTHS_3[self.data.month]
  168. def c(self):
  169. """
  170. ISO 8601 Format
  171. Example : '2008-01-02T10:30:00.000123'
  172. """
  173. return self.data.isoformat()
  174. def d(self):
  175. "Day of the month, 2 digits with leading zeros; i.e. '01' to '31'"
  176. return '%02d' % self.data.day
  177. def D(self):
  178. "Day of the week, textual, 3 letters; e.g. 'Fri'"
  179. return WEEKDAYS_ABBR[self.data.weekday()]
  180. def E(self):
  181. "Alternative month names as required by some locales. Proprietary extension."
  182. return MONTHS_ALT[self.data.month]
  183. def F(self):
  184. "Month, textual, long; e.g. 'January'"
  185. return MONTHS[self.data.month]
  186. def I(self):
  187. "'1' if Daylight Savings Time, '0' otherwise."
  188. if self.timezone and self.timezone.dst(self.data):
  189. return '1'
  190. else:
  191. return '0'
  192. def j(self):
  193. "Day of the month without leading zeros; i.e. '1' to '31'"
  194. return self.data.day
  195. def l(self):
  196. "Day of the week, textual, long; e.g. 'Friday'"
  197. return WEEKDAYS[self.data.weekday()]
  198. def L(self):
  199. "Boolean for whether it is a leap year; i.e. True or False"
  200. return calendar.isleap(self.data.year)
  201. def m(self):
  202. "Month; i.e. '01' to '12'"
  203. return '%02d' % self.data.month
  204. def M(self):
  205. "Month, textual, 3 letters; e.g. 'Jan'"
  206. return MONTHS_3[self.data.month].title()
  207. def n(self):
  208. "Month without leading zeros; i.e. '1' to '12'"
  209. return self.data.month
  210. def N(self):
  211. "Month abbreviation in Associated Press style. Proprietary extension."
  212. return MONTHS_AP[self.data.month]
  213. def o(self):
  214. "ISO 8601 year number matching the ISO week number (W)"
  215. return self.data.isocalendar()[0]
  216. def r(self):
  217. "RFC 2822 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'"
  218. return self.format('D, j M Y H:i:s O')
  219. def S(self):
  220. "English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th'"
  221. if self.data.day in (11, 12, 13): # Special case
  222. return 'th'
  223. last = self.data.day % 10
  224. if last == 1:
  225. return 'st'
  226. if last == 2:
  227. return 'nd'
  228. if last == 3:
  229. return 'rd'
  230. return 'th'
  231. def t(self):
  232. "Number of days in the given month; i.e. '28' to '31'"
  233. return '%02d' % calendar.monthrange(self.data.year, self.data.month)[1]
  234. def U(self):
  235. "Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)"
  236. if isinstance(self.data, datetime.datetime) and is_aware(self.data):
  237. return int(calendar.timegm(self.data.utctimetuple()))
  238. else:
  239. return int(time.mktime(self.data.timetuple()))
  240. def w(self):
  241. "Day of the week, numeric, i.e. '0' (Sunday) to '6' (Saturday)"
  242. return (self.data.weekday() + 1) % 7
  243. def W(self):
  244. "ISO-8601 week number of year, weeks starting on Monday"
  245. # Algorithm from http://www.personal.ecu.edu/mccartyr/ISOwdALG.txt
  246. week_number = None
  247. jan1_weekday = self.data.replace(month=1, day=1).weekday() + 1
  248. weekday = self.data.weekday() + 1
  249. day_of_year = self.z()
  250. if day_of_year <= (8 - jan1_weekday) and jan1_weekday > 4:
  251. if jan1_weekday == 5 or (jan1_weekday == 6 and calendar.isleap(self.data.year - 1)):
  252. week_number = 53
  253. else:
  254. week_number = 52
  255. else:
  256. if calendar.isleap(self.data.year):
  257. i = 366
  258. else:
  259. i = 365
  260. if (i - day_of_year) < (4 - weekday):
  261. week_number = 1
  262. else:
  263. j = day_of_year + (7 - weekday) + (jan1_weekday - 1)
  264. week_number = j // 7
  265. if jan1_weekday > 4:
  266. week_number -= 1
  267. return week_number
  268. def y(self):
  269. "Year, 2 digits; e.g. '99'"
  270. return six.text_type(self.data.year)[2:]
  271. def Y(self):
  272. "Year, 4 digits; e.g. '1999'"
  273. return self.data.year
  274. def z(self):
  275. "Day of the year; i.e. '0' to '365'"
  276. doy = self.year_days[self.data.month] + self.data.day
  277. if self.L() and self.data.month > 2:
  278. doy += 1
  279. return doy
  280. def format(value, format_string):
  281. "Convenience function"
  282. df = DateFormat(value)
  283. return df.format(format_string)
  284. def time_format(value, format_string):
  285. "Convenience function"
  286. tf = TimeFormat(value)
  287. return tf.format(format_string)