Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. """
  2. PHP date() style date formatting
  3. See https://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. 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 datetime.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. # We only support timezone when formatting datetime objects,
  52. # not date objects (timezone information not appropriate),
  53. # or time objects (against established django policy).
  54. if isinstance(obj, datetime.datetime):
  55. if is_naive(obj):
  56. self.timezone = get_default_timezone()
  57. else:
  58. self.timezone = obj.tzinfo
  59. @property
  60. def _no_timezone_or_datetime_is_ambiguous_or_imaginary(self):
  61. return not self.timezone or _datetime_ambiguous_or_imaginary(
  62. self.data, self.timezone
  63. )
  64. def a(self):
  65. "'a.m.' or 'p.m.'"
  66. if self.data.hour > 11:
  67. return _("p.m.")
  68. return _("a.m.")
  69. def A(self):
  70. "'AM' or 'PM'"
  71. if self.data.hour > 11:
  72. return _("PM")
  73. return _("AM")
  74. def e(self):
  75. """
  76. Timezone name.
  77. If timezone information is not available, return an empty string.
  78. """
  79. if not self.timezone:
  80. return ""
  81. try:
  82. if hasattr(self.data, "tzinfo") and self.data.tzinfo:
  83. return self.data.tzname() or ""
  84. except NotImplementedError:
  85. pass
  86. return ""
  87. def f(self):
  88. """
  89. Time, in 12-hour hours and minutes, with minutes left off if they're
  90. zero.
  91. Examples: '1', '1:30', '2:05', '2'
  92. Proprietary extension.
  93. """
  94. hour = self.data.hour % 12 or 12
  95. minute = self.data.minute
  96. return "%d:%02d" % (hour, minute) if minute else hour
  97. def g(self):
  98. "Hour, 12-hour format without leading zeros; i.e. '1' to '12'"
  99. return self.data.hour % 12 or 12
  100. def G(self):
  101. "Hour, 24-hour format without leading zeros; i.e. '0' to '23'"
  102. return self.data.hour
  103. def h(self):
  104. "Hour, 12-hour format; i.e. '01' to '12'"
  105. return "%02d" % (self.data.hour % 12 or 12)
  106. def H(self):
  107. "Hour, 24-hour format; i.e. '00' to '23'"
  108. return "%02d" % self.data.hour
  109. def i(self):
  110. "Minutes; i.e. '00' to '59'"
  111. return "%02d" % self.data.minute
  112. def O(self): # NOQA: E743, E741
  113. """
  114. Difference to Greenwich time in hours; e.g. '+0200', '-0430'.
  115. If timezone information is not available, return an empty string.
  116. """
  117. if self._no_timezone_or_datetime_is_ambiguous_or_imaginary:
  118. return ""
  119. seconds = self.Z()
  120. sign = "-" if seconds < 0 else "+"
  121. seconds = abs(seconds)
  122. return "%s%02d%02d" % (sign, seconds // 3600, (seconds // 60) % 60)
  123. def P(self):
  124. """
  125. Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off
  126. if they're zero and the strings 'midnight' and 'noon' if appropriate.
  127. Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.'
  128. Proprietary extension.
  129. """
  130. if self.data.minute == 0 and self.data.hour == 0:
  131. return _("midnight")
  132. if self.data.minute == 0 and self.data.hour == 12:
  133. return _("noon")
  134. return "%s %s" % (self.f(), self.a())
  135. def s(self):
  136. "Seconds; i.e. '00' to '59'"
  137. return "%02d" % self.data.second
  138. def T(self):
  139. """
  140. Time zone of this machine; e.g. 'EST' or 'MDT'.
  141. If timezone information is not available, return an empty string.
  142. """
  143. if self._no_timezone_or_datetime_is_ambiguous_or_imaginary:
  144. return ""
  145. return str(self.timezone.tzname(self.data))
  146. def u(self):
  147. "Microseconds; i.e. '000000' to '999999'"
  148. return "%06d" % self.data.microsecond
  149. def Z(self):
  150. """
  151. Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for
  152. timezones west of UTC is always negative, and for those east of UTC is
  153. always positive.
  154. If timezone information is not available, return an empty string.
  155. """
  156. if self._no_timezone_or_datetime_is_ambiguous_or_imaginary:
  157. return ""
  158. offset = self.timezone.utcoffset(self.data)
  159. # `offset` is a datetime.timedelta. For negative values (to the west of
  160. # UTC) only days can be negative (days=-1) and seconds are always
  161. # positive. e.g. UTC-1 -> timedelta(days=-1, seconds=82800, microseconds=0)
  162. # Positive offsets have days=0
  163. return offset.days * 86400 + offset.seconds
  164. class DateFormat(TimeFormat):
  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): # NOQA: E743, E741
  187. "'1' if daylight saving time, '0' otherwise."
  188. if self._no_timezone_or_datetime_is_ambiguous_or_imaginary:
  189. return ""
  190. return "1" if self.timezone.dst(self.data) else "0"
  191. def j(self):
  192. "Day of the month without leading zeros; i.e. '1' to '31'"
  193. return self.data.day
  194. def l(self): # NOQA: E743, E741
  195. "Day of the week, textual, long; e.g. 'Friday'"
  196. return WEEKDAYS[self.data.weekday()]
  197. def L(self):
  198. "Boolean for whether it is a leap year; i.e. True or False"
  199. return calendar.isleap(self.data.year)
  200. def m(self):
  201. "Month; i.e. '01' to '12'"
  202. return "%02d" % self.data.month
  203. def M(self):
  204. "Month, textual, 3 letters; e.g. 'Jan'"
  205. return MONTHS_3[self.data.month].title()
  206. def n(self):
  207. "Month without leading zeros; i.e. '1' to '12'"
  208. return self.data.month
  209. def N(self):
  210. "Month abbreviation in Associated Press style. Proprietary extension."
  211. return MONTHS_AP[self.data.month]
  212. def o(self):
  213. "ISO 8601 year number matching the ISO week number (W)"
  214. return self.data.isocalendar()[0]
  215. def r(self):
  216. "RFC 5322 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'"
  217. if type(self.data) is datetime.date:
  218. raise TypeError(
  219. "The format for date objects may not contain time-related "
  220. "format specifiers (found 'r')."
  221. )
  222. if is_naive(self.data):
  223. dt = make_aware(self.data, timezone=self.timezone)
  224. else:
  225. dt = self.data
  226. return format_datetime_rfc5322(dt)
  227. def S(self):
  228. """
  229. English ordinal suffix for the day of the month, 2 characters; i.e.
  230. 'st', 'nd', 'rd' or 'th'.
  231. """
  232. if self.data.day in (11, 12, 13): # Special case
  233. return "th"
  234. last = self.data.day % 10
  235. if last == 1:
  236. return "st"
  237. if last == 2:
  238. return "nd"
  239. if last == 3:
  240. return "rd"
  241. return "th"
  242. def t(self):
  243. "Number of days in the given month; i.e. '28' to '31'"
  244. return "%02d" % calendar.monthrange(self.data.year, self.data.month)[1]
  245. def U(self):
  246. "Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)"
  247. value = self.data
  248. if not isinstance(value, datetime.datetime):
  249. value = datetime.datetime.combine(value, datetime.time.min)
  250. return int(value.timestamp())
  251. def w(self):
  252. "Day of the week, numeric, i.e. '0' (Sunday) to '6' (Saturday)"
  253. return (self.data.weekday() + 1) % 7
  254. def W(self):
  255. "ISO-8601 week number of year, weeks starting on Monday"
  256. return self.data.isocalendar()[1]
  257. def y(self):
  258. """Year, 2 digits with leading zeros; e.g. '99'."""
  259. return "%02d" % (self.data.year % 100)
  260. def Y(self):
  261. """Year, 4 digits with leading zeros; e.g. '1999'."""
  262. return "%04d" % self.data.year
  263. def z(self):
  264. """Day of the year, i.e. 1 to 366."""
  265. return self.data.timetuple().tm_yday
  266. def format(value, format_string):
  267. "Convenience function"
  268. df = DateFormat(value)
  269. return df.format(format_string)
  270. def time_format(value, format_string):
  271. "Convenience function"
  272. tf = TimeFormat(value)
  273. return tf.format(format_string)