dateformat.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. """
  2. PHP date() style date formatting
  3. See https://www.php.net/date for format strings
  4. Usage:
  5. >>> from datetime import datetime
  6. >>> d = 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. from datetime import date, datetime, time
  14. from email.utils import format_datetime as format_datetime_rfc5322
  15. from django.utils.dates import (
  16. MONTHS,
  17. MONTHS_3,
  18. MONTHS_ALT,
  19. MONTHS_AP,
  20. WEEKDAYS,
  21. WEEKDAYS_ABBR,
  22. )
  23. from django.utils.regex_helper import _lazy_re_compile
  24. from django.utils.timezone import (
  25. _datetime_ambiguous_or_imaginary,
  26. get_default_timezone,
  27. is_naive,
  28. make_aware,
  29. )
  30. from django.utils.translation import gettext as _
  31. re_formatchars = _lazy_re_compile(r"(?<!\\)([aAbcdDeEfFgGhHiIjlLmMnNoOPrsStTUuwWyYzZ])")
  32. re_escaped = _lazy_re_compile(r"\\(.)")
  33. class Formatter:
  34. def format(self, formatstr):
  35. pieces = []
  36. for i, piece in enumerate(re_formatchars.split(str(formatstr))):
  37. if i % 2:
  38. if type(self.data) is date and hasattr(TimeFormat, piece):
  39. raise TypeError(
  40. "The format for date objects may not contain "
  41. "time-related format specifiers (found '%s')." % piece
  42. )
  43. pieces.append(str(getattr(self, piece)()))
  44. elif piece:
  45. pieces.append(re_escaped.sub(r"\1", piece))
  46. return "".join(pieces)
  47. class TimeFormat(Formatter):
  48. def __init__(self, obj):
  49. self.data = obj
  50. self.timezone = None
  51. if isinstance(obj, datetime):
  52. # Timezone is only supported when formatting datetime objects, not
  53. # date objects (timezone information not appropriate), or time
  54. # objects (against established django policy).
  55. if is_naive(obj):
  56. timezone = get_default_timezone()
  57. else:
  58. timezone = obj.tzinfo
  59. if not _datetime_ambiguous_or_imaginary(obj, timezone):
  60. self.timezone = timezone
  61. def a(self):
  62. "'a.m.' or 'p.m.'"
  63. if self.data.hour > 11:
  64. return _("p.m.")
  65. return _("a.m.")
  66. def A(self):
  67. "'AM' or 'PM'"
  68. if self.data.hour > 11:
  69. return _("PM")
  70. return _("AM")
  71. def e(self):
  72. """
  73. Timezone name.
  74. If timezone information is not available, return an empty string.
  75. """
  76. if not self.timezone:
  77. return ""
  78. try:
  79. if getattr(self.data, "tzinfo", None):
  80. return self.data.tzname() or ""
  81. except NotImplementedError:
  82. pass
  83. return ""
  84. def f(self):
  85. """
  86. Time, in 12-hour hours and minutes, with minutes left off if they're
  87. zero.
  88. Examples: '1', '1:30', '2:05', '2'
  89. Proprietary extension.
  90. """
  91. hour = self.data.hour % 12 or 12
  92. minute = self.data.minute
  93. return "%d:%02d" % (hour, minute) if minute else hour
  94. def g(self):
  95. "Hour, 12-hour format without leading zeros; i.e. '1' to '12'"
  96. return self.data.hour % 12 or 12
  97. def G(self):
  98. "Hour, 24-hour format without leading zeros; i.e. '0' to '23'"
  99. return self.data.hour
  100. def h(self):
  101. "Hour, 12-hour format; i.e. '01' to '12'"
  102. return "%02d" % (self.data.hour % 12 or 12)
  103. def H(self):
  104. "Hour, 24-hour format; i.e. '00' to '23'"
  105. return "%02d" % self.data.hour
  106. def i(self):
  107. "Minutes; i.e. '00' to '59'"
  108. return "%02d" % self.data.minute
  109. def O(self): # NOQA: E743, E741
  110. """
  111. Difference to Greenwich time in hours; e.g. '+0200', '-0430'.
  112. If timezone information is not available, return an empty string.
  113. """
  114. if self.timezone is None:
  115. return ""
  116. offset = self.timezone.utcoffset(self.data)
  117. seconds = offset.days * 86400 + offset.seconds
  118. sign = "-" if seconds < 0 else "+"
  119. seconds = abs(seconds)
  120. return "%s%02d%02d" % (sign, seconds // 3600, (seconds // 60) % 60)
  121. def P(self):
  122. """
  123. Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off
  124. if they're zero and the strings 'midnight' and 'noon' if appropriate.
  125. Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.'
  126. Proprietary extension.
  127. """
  128. if self.data.minute == 0 and self.data.hour == 0:
  129. return _("midnight")
  130. if self.data.minute == 0 and self.data.hour == 12:
  131. return _("noon")
  132. return "%s %s" % (self.f(), self.a())
  133. def s(self):
  134. "Seconds; i.e. '00' to '59'"
  135. return "%02d" % self.data.second
  136. def T(self):
  137. """
  138. Time zone of this machine; e.g. 'EST' or 'MDT'.
  139. If timezone information is not available, return an empty string.
  140. """
  141. if self.timezone is None:
  142. return ""
  143. return str(self.timezone.tzname(self.data))
  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, return an empty string.
  153. """
  154. if self.timezone is None:
  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 saving time, '0' otherwise."
  186. if self.timezone is None:
  187. return ""
  188. return "1" if self.timezone.dst(self.data) else "0"
  189. def j(self):
  190. "Day of the month without leading zeros; i.e. '1' to '31'"
  191. return self.data.day
  192. def l(self): # NOQA: E743, E741
  193. "Day of the week, textual, long; e.g. 'Friday'"
  194. return WEEKDAYS[self.data.weekday()]
  195. def L(self):
  196. "Boolean for whether it is a leap year; i.e. True or False"
  197. return calendar.isleap(self.data.year)
  198. def m(self):
  199. "Month; i.e. '01' to '12'"
  200. return "%02d" % self.data.month
  201. def M(self):
  202. "Month, textual, 3 letters; e.g. 'Jan'"
  203. return MONTHS_3[self.data.month].title()
  204. def n(self):
  205. "Month without leading zeros; i.e. '1' to '12'"
  206. return self.data.month
  207. def N(self):
  208. "Month abbreviation in Associated Press style. Proprietary extension."
  209. return MONTHS_AP[self.data.month]
  210. def o(self):
  211. "ISO 8601 year number matching the ISO week number (W)"
  212. return self.data.isocalendar().year
  213. def r(self):
  214. "RFC 5322 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'"
  215. value = self.data
  216. if not isinstance(value, datetime):
  217. # Assume midnight in default timezone if datetime.date provided.
  218. default_timezone = get_default_timezone()
  219. value = datetime.combine(value, time.min).replace(tzinfo=default_timezone)
  220. elif is_naive(value):
  221. value = make_aware(value, timezone=self.timezone)
  222. return format_datetime_rfc5322(value)
  223. def S(self):
  224. """
  225. English ordinal suffix for the day of the month, 2 characters; i.e.
  226. 'st', 'nd', 'rd' or 'th'.
  227. """
  228. if self.data.day in (11, 12, 13): # Special case
  229. return "th"
  230. last = self.data.day % 10
  231. if last == 1:
  232. return "st"
  233. if last == 2:
  234. return "nd"
  235. if last == 3:
  236. return "rd"
  237. return "th"
  238. def t(self):
  239. "Number of days in the given month; i.e. '28' to '31'"
  240. return calendar.monthrange(self.data.year, self.data.month)[1]
  241. def U(self):
  242. "Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)"
  243. value = self.data
  244. if not isinstance(value, datetime):
  245. value = datetime.combine(value, time.min)
  246. return int(value.timestamp())
  247. def w(self):
  248. "Day of the week, numeric, i.e. '0' (Sunday) to '6' (Saturday)"
  249. return (self.data.weekday() + 1) % 7
  250. def W(self):
  251. "ISO-8601 week number of year, weeks starting on Monday"
  252. return self.data.isocalendar().week
  253. def y(self):
  254. """Year, 2 digits with leading zeros; e.g. '99'."""
  255. return "%02d" % (self.data.year % 100)
  256. def Y(self):
  257. """Year, 4 digits with leading zeros; e.g. '1999'."""
  258. return "%04d" % self.data.year
  259. def z(self):
  260. """Day of the year, i.e. 1 to 366."""
  261. return self.data.timetuple().tm_yday
  262. def format(value, format_string):
  263. "Convenience function"
  264. df = DateFormat(value)
  265. return df.format(format_string)
  266. def time_format(value, format_string):
  267. "Convenience function"
  268. tf = TimeFormat(value)
  269. return tf.format(format_string)