PageRenderTime 26ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/django/utils/dateformat.py

http://github.com/django/django
Python | 349 lines | 336 code | 0 blank | 13 comment | 3 complexity | 19ac79a939a09cd7ef7c9e5b6b8d687c MD5 | raw file
Possible License(s): BSD-3-Clause, MIT
  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. import calendar
  13. import datetime
  14. import time
  15. from email.utils import format_datetime as format_datetime_rfc5322
  16. from django.utils.dates import (
  17. MONTHS, MONTHS_3, MONTHS_ALT, MONTHS_AP, WEEKDAYS, WEEKDAYS_ABBR,
  18. )
  19. from django.utils.regex_helper import _lazy_re_compile
  20. from django.utils.timezone import (
  21. get_default_timezone, is_aware, is_naive, make_aware,
  22. )
  23. from django.utils.translation import gettext as _
  24. re_formatchars = _lazy_re_compile(r'(?<!\\)([aAbcdDeEfFgGhHiIjlLmMnNoOPrsStTUuwWyYzZ])')
  25. re_escaped = _lazy_re_compile(r'\\(.)')
  26. class Formatter:
  27. def format(self, formatstr):
  28. pieces = []
  29. for i, piece in enumerate(re_formatchars.split(str(formatstr))):
  30. if i % 2:
  31. if type(self.data) is datetime.date and hasattr(TimeFormat, piece):
  32. raise TypeError(
  33. "The format for date objects may not contain "
  34. "time-related format specifiers (found '%s')." % piece
  35. )
  36. pieces.append(str(getattr(self, piece)()))
  37. elif piece:
  38. pieces.append(re_escaped.sub(r'\1', piece))
  39. return ''.join(pieces)
  40. class TimeFormat(Formatter):
  41. def __init__(self, obj):
  42. self.data = obj
  43. self.timezone = None
  44. # We only support timezone when formatting datetime objects,
  45. # not date objects (timezone information not appropriate),
  46. # or time objects (against established django policy).
  47. if isinstance(obj, datetime.datetime):
  48. if is_naive(obj):
  49. self.timezone = get_default_timezone()
  50. else:
  51. self.timezone = obj.tzinfo
  52. def a(self):
  53. "'a.m.' or 'p.m.'"
  54. if self.data.hour > 11:
  55. return _('p.m.')
  56. return _('a.m.')
  57. def A(self):
  58. "'AM' or 'PM'"
  59. if self.data.hour > 11:
  60. return _('PM')
  61. return _('AM')
  62. def e(self):
  63. """
  64. Timezone name.
  65. If timezone information is not available, return an empty string.
  66. """
  67. if not self.timezone:
  68. return ""
  69. try:
  70. if hasattr(self.data, 'tzinfo') and self.data.tzinfo:
  71. return self.data.tzname() or ''
  72. except NotImplementedError:
  73. pass
  74. return ""
  75. def f(self):
  76. """
  77. Time, in 12-hour hours and minutes, with minutes left off if they're
  78. zero.
  79. Examples: '1', '1:30', '2:05', '2'
  80. Proprietary extension.
  81. """
  82. if self.data.minute == 0:
  83. return self.g()
  84. return '%s:%s' % (self.g(), self.i())
  85. def g(self):
  86. "Hour, 12-hour format without leading zeros; i.e. '1' to '12'"
  87. if self.data.hour == 0:
  88. return 12
  89. if self.data.hour > 12:
  90. return self.data.hour - 12
  91. return self.data.hour
  92. def G(self):
  93. "Hour, 24-hour format without leading zeros; i.e. '0' to '23'"
  94. return self.data.hour
  95. def h(self):
  96. "Hour, 12-hour format; i.e. '01' to '12'"
  97. return '%02d' % self.g()
  98. def H(self):
  99. "Hour, 24-hour format; i.e. '00' to '23'"
  100. return '%02d' % self.G()
  101. def i(self):
  102. "Minutes; i.e. '00' to '59'"
  103. return '%02d' % self.data.minute
  104. def O(self): # NOQA: E743
  105. """
  106. Difference to Greenwich time in hours; e.g. '+0200', '-0430'.
  107. If timezone information is not available, return an empty string.
  108. """
  109. if not self.timezone:
  110. return ""
  111. seconds = self.Z()
  112. if seconds == "":
  113. return ""
  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, return an empty string.
  136. """
  137. if not self.timezone:
  138. return ""
  139. name = None
  140. try:
  141. name = self.timezone.tzname(self.data)
  142. except Exception:
  143. # pytz raises AmbiguousTimeError during the autumn DST change.
  144. # This happens mainly when __init__ receives a naive datetime
  145. # and sets self.timezone = get_default_timezone().
  146. pass
  147. if name is None:
  148. name = self.format('O')
  149. return str(name)
  150. def u(self):
  151. "Microseconds; i.e. '000000' to '999999'"
  152. return '%06d' % self.data.microsecond
  153. def Z(self):
  154. """
  155. Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for
  156. timezones west of UTC is always negative, and for those east of UTC is
  157. always positive.
  158. If timezone information is not available, return an empty string.
  159. """
  160. if not self.timezone:
  161. return ""
  162. try:
  163. offset = self.timezone.utcoffset(self.data)
  164. except Exception:
  165. # pytz raises AmbiguousTimeError during the autumn DST change.
  166. # This happens mainly when __init__ receives a naive datetime
  167. # and sets self.timezone = get_default_timezone().
  168. return ""
  169. # `offset` is a datetime.timedelta. For negative values (to the west of
  170. # UTC) only days can be negative (days=-1) and seconds are always
  171. # positive. e.g. UTC-1 -> timedelta(days=-1, seconds=82800, microseconds=0)
  172. # Positive offsets have days=0
  173. return offset.days * 86400 + offset.seconds
  174. class DateFormat(TimeFormat):
  175. def b(self):
  176. "Month, textual, 3 letters, lowercase; e.g. 'jan'"
  177. return MONTHS_3[self.data.month]
  178. def c(self):
  179. """
  180. ISO 8601 Format
  181. Example : '2008-01-02T10:30:00.000123'
  182. """
  183. return self.data.isoformat()
  184. def d(self):
  185. "Day of the month, 2 digits with leading zeros; i.e. '01' to '31'"
  186. return '%02d' % self.data.day
  187. def D(self):
  188. "Day of the week, textual, 3 letters; e.g. 'Fri'"
  189. return WEEKDAYS_ABBR[self.data.weekday()]
  190. def E(self):
  191. "Alternative month names as required by some locales. Proprietary extension."
  192. return MONTHS_ALT[self.data.month]
  193. def F(self):
  194. "Month, textual, long; e.g. 'January'"
  195. return MONTHS[self.data.month]
  196. def I(self): # NOQA: E743
  197. "'1' if Daylight Savings Time, '0' otherwise."
  198. try:
  199. if self.timezone and self.timezone.dst(self.data):
  200. return '1'
  201. else:
  202. return '0'
  203. except Exception:
  204. # pytz raises AmbiguousTimeError during the autumn DST change.
  205. # This happens mainly when __init__ receives a naive datetime
  206. # and sets self.timezone = get_default_timezone().
  207. return ''
  208. def j(self):
  209. "Day of the month without leading zeros; i.e. '1' to '31'"
  210. return self.data.day
  211. def l(self): # NOQA: E743
  212. "Day of the week, textual, long; e.g. 'Friday'"
  213. return WEEKDAYS[self.data.weekday()]
  214. def L(self):
  215. "Boolean for whether it is a leap year; i.e. True or False"
  216. return calendar.isleap(self.data.year)
  217. def m(self):
  218. "Month; i.e. '01' to '12'"
  219. return '%02d' % self.data.month
  220. def M(self):
  221. "Month, textual, 3 letters; e.g. 'Jan'"
  222. return MONTHS_3[self.data.month].title()
  223. def n(self):
  224. "Month without leading zeros; i.e. '1' to '12'"
  225. return self.data.month
  226. def N(self):
  227. "Month abbreviation in Associated Press style. Proprietary extension."
  228. return MONTHS_AP[self.data.month]
  229. def o(self):
  230. "ISO 8601 year number matching the ISO week number (W)"
  231. return self.data.isocalendar()[0]
  232. def r(self):
  233. "RFC 5322 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'"
  234. if type(self.data) is datetime.date:
  235. raise TypeError(
  236. "The format for date objects may not contain time-related "
  237. "format specifiers (found 'r')."
  238. )
  239. if is_naive(self.data):
  240. dt = make_aware(self.data, timezone=self.timezone)
  241. else:
  242. dt = self.data
  243. return format_datetime_rfc5322(dt)
  244. def S(self):
  245. "English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th'"
  246. if self.data.day in (11, 12, 13): # Special case
  247. return 'th'
  248. last = self.data.day % 10
  249. if last == 1:
  250. return 'st'
  251. if last == 2:
  252. return 'nd'
  253. if last == 3:
  254. return 'rd'
  255. return 'th'
  256. def t(self):
  257. "Number of days in the given month; i.e. '28' to '31'"
  258. return '%02d' % calendar.monthrange(self.data.year, self.data.month)[1]
  259. def U(self):
  260. "Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)"
  261. if isinstance(self.data, datetime.datetime) and is_aware(self.data):
  262. return int(calendar.timegm(self.data.utctimetuple()))
  263. else:
  264. return int(time.mktime(self.data.timetuple()))
  265. def w(self):
  266. "Day of the week, numeric, i.e. '0' (Sunday) to '6' (Saturday)"
  267. return (self.data.weekday() + 1) % 7
  268. def W(self):
  269. "ISO-8601 week number of year, weeks starting on Monday"
  270. return self.data.isocalendar()[1]
  271. def y(self):
  272. "Year, 2 digits; e.g. '99'"
  273. return str(self.data.year)[2:]
  274. def Y(self):
  275. "Year, 4 digits; e.g. '1999'"
  276. return self.data.year
  277. def z(self):
  278. """Day of the year, i.e. 1 to 366."""
  279. return self.data.timetuple().tm_yday
  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)