dateformat.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. _datetime_ambiguous_or_imaginary, get_default_timezone, is_aware, is_naive,
  22. make_aware,
  23. )
  24. from django.utils.translation import gettext as _
  25. re_formatchars = _lazy_re_compile(r'(?<!\\)([aAbcdDeEfFgGhHiIjlLmMnNoOPrsStTUuwWyYzZ])')
  26. re_escaped = _lazy_re_compile(r'\\(.)')
  27. class Formatter:
  28. def format(self, formatstr):
  29. pieces = []
  30. for i, piece in enumerate(re_formatchars.split(str(formatstr))):
  31. if i % 2:
  32. if type(self.data) is datetime.date and hasattr(TimeFormat, piece):
  33. raise TypeError(
  34. "The format for date objects may not contain "
  35. "time-related format specifiers (found '%s')." % piece
  36. )
  37. pieces.append(str(getattr(self, piece)()))
  38. elif piece:
  39. pieces.append(re_escaped.sub(r'\1', piece))
  40. return ''.join(pieces)
  41. class TimeFormat(Formatter):
  42. def __init__(self, obj):
  43. self.data = obj
  44. self.timezone = None
  45. # We only support timezone when formatting datetime objects,
  46. # not date objects (timezone information not appropriate),
  47. # or time objects (against established django policy).
  48. if isinstance(obj, datetime.datetime):
  49. if is_naive(obj):
  50. self.timezone = get_default_timezone()
  51. else:
  52. self.timezone = obj.tzinfo
  53. def a(self):
  54. "'a.m.' or 'p.m.'"
  55. if self.data.hour > 11:
  56. return _('p.m.')
  57. return _('a.m.')
  58. def A(self):
  59. "'AM' or 'PM'"
  60. if self.data.hour > 11:
  61. return _('PM')
  62. return _('AM')
  63. def e(self):
  64. """
  65. Timezone name.
  66. If timezone information is not available, return an empty string.
  67. """
  68. if not self.timezone:
  69. return ""
  70. try:
  71. if hasattr(self.data, 'tzinfo') and self.data.tzinfo:
  72. return self.data.tzname() 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. return self.data.hour % 12 or 12
  89. def G(self):
  90. "Hour, 24-hour format without leading zeros; i.e. '0' to '23'"
  91. return self.data.hour
  92. def h(self):
  93. "Hour, 12-hour format; i.e. '01' to '12'"
  94. return '%02d' % self.g()
  95. def H(self):
  96. "Hour, 24-hour format; i.e. '00' to '23'"
  97. return '%02d' % self.G()
  98. def i(self):
  99. "Minutes; i.e. '00' to '59'"
  100. return '%02d' % self.data.minute
  101. def O(self): # NOQA: E743, E741
  102. """
  103. Difference to Greenwich time in hours; e.g. '+0200', '-0430'.
  104. If timezone information is not available, return an empty string.
  105. """
  106. if not self.timezone:
  107. return ""
  108. seconds = self.Z()
  109. if seconds == "":
  110. return ""
  111. sign = '-' if seconds < 0 else '+'
  112. seconds = abs(seconds)
  113. return "%s%02d%02d" % (sign, seconds // 3600, (seconds // 60) % 60)
  114. def P(self):
  115. """
  116. Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off
  117. if they're zero and the strings 'midnight' and 'noon' if appropriate.
  118. Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.'
  119. Proprietary extension.
  120. """
  121. if self.data.minute == 0 and self.data.hour == 0:
  122. return _('midnight')
  123. if self.data.minute == 0 and self.data.hour == 12:
  124. return _('noon')
  125. return '%s %s' % (self.f(), self.a())
  126. def s(self):
  127. "Seconds; i.e. '00' to '59'"
  128. return '%02d' % self.data.second
  129. def T(self):
  130. """
  131. Time zone of this machine; e.g. 'EST' or 'MDT'.
  132. If timezone information is not available, return an empty string.
  133. """
  134. if not self.timezone:
  135. return ""
  136. if not _datetime_ambiguous_or_imaginary(self.data, self.timezone):
  137. name = self.timezone.tzname(self.data)
  138. else:
  139. name = self.format('O')
  140. return str(name)
  141. def u(self):
  142. "Microseconds; i.e. '000000' to '999999'"
  143. return '%06d' % self.data.microsecond
  144. def Z(self):
  145. """
  146. Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for
  147. timezones west of UTC is always negative, and for those east of UTC is
  148. always positive.
  149. If timezone information is not available, return an empty string.
  150. """
  151. if (
  152. not self.timezone or
  153. _datetime_ambiguous_or_imaginary(self.data, self.timezone)
  154. ):
  155. return ""
  156. offset = self.timezone.utcoffset(self.data)
  157. # `offset` is a datetime.timedelta. For negative values (to the west of
  158. # UTC) only days can be negative (days=-1) and seconds are always
  159. # positive. e.g. UTC-1 -> timedelta(days=-1, seconds=82800, microseconds=0)
  160. # Positive offsets have days=0
  161. return offset.days * 86400 + offset.seconds
  162. class DateFormat(TimeFormat):
  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): # NOQA: E743, E741
  185. "'1' if Daylight Savings Time, '0' otherwise."
  186. if (
  187. not self.timezone or
  188. _datetime_ambiguous_or_imaginary(self.data, self.timezone)
  189. ):
  190. return ''
  191. return '1' if self.timezone.dst(self.data) else '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): # NOQA: E743, E741
  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 5322 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'"
  218. if type(self.data) is datetime.date:
  219. raise TypeError(
  220. "The format for date objects may not contain time-related "
  221. "format specifiers (found 'r')."
  222. )
  223. if is_naive(self.data):
  224. dt = make_aware(self.data, timezone=self.timezone)
  225. else:
  226. dt = self.data
  227. return format_datetime_rfc5322(dt)
  228. def S(self):
  229. "English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th'"
  230. if self.data.day in (11, 12, 13): # Special case
  231. return 'th'
  232. last = self.data.day % 10
  233. if last == 1:
  234. return 'st'
  235. if last == 2:
  236. return 'nd'
  237. if last == 3:
  238. return 'rd'
  239. return 'th'
  240. def t(self):
  241. "Number of days in the given month; i.e. '28' to '31'"
  242. return '%02d' % calendar.monthrange(self.data.year, self.data.month)[1]
  243. def U(self):
  244. "Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)"
  245. if isinstance(self.data, datetime.datetime) and is_aware(self.data):
  246. return int(calendar.timegm(self.data.utctimetuple()))
  247. else:
  248. return int(time.mktime(self.data.timetuple()))
  249. def w(self):
  250. "Day of the week, numeric, i.e. '0' (Sunday) to '6' (Saturday)"
  251. return (self.data.weekday() + 1) % 7
  252. def W(self):
  253. "ISO-8601 week number of year, weeks starting on Monday"
  254. return self.data.isocalendar()[1]
  255. def y(self):
  256. """Year, 2 digits with leading zeros; e.g. '99'."""
  257. return '%02d' % (self.data.year % 100)
  258. def Y(self):
  259. """Year, 4 digits with leading zeros; e.g. '1999'."""
  260. return '%04d' % self.data.year
  261. def z(self):
  262. """Day of the year, i.e. 1 to 366."""
  263. return self.data.timetuple().tm_yday
  264. def format(value, format_string):
  265. "Convenience function"
  266. df = DateFormat(value)
  267. return df.format(format_string)
  268. def time_format(value, format_string):
  269. "Convenience function"
  270. tf = TimeFormat(value)
  271. return tf.format(format_string)