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 11KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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 re
  15. import time
  16. from django.utils.dates import (
  17. MONTHS, MONTHS_3, MONTHS_ALT, MONTHS_AP, WEEKDAYS, WEEKDAYS_ABBR,
  18. )
  19. from django.utils.timezone import get_default_timezone, is_aware, is_naive
  20. from django.utils.translation import gettext as _
  21. re_formatchars = re.compile(r'(?<!\\)([aAbBcdDeEfFgGhHiIjlLmMnNoOPrsStTUuwWyYzZ])')
  22. re_escaped = re.compile(r'\\(.)')
  23. class Formatter:
  24. def format(self, formatstr):
  25. pieces = []
  26. for i, piece in enumerate(re_formatchars.split(str(formatstr))):
  27. if i % 2:
  28. if type(self.data) is datetime.date and hasattr(TimeFormat, piece):
  29. raise TypeError(
  30. "The format for date objects may not contain "
  31. "time-related format specifiers (found '%s')." % piece
  32. )
  33. pieces.append(str(getattr(self, piece)()))
  34. elif piece:
  35. pieces.append(re_escaped.sub(r'\1', piece))
  36. return ''.join(pieces)
  37. class TimeFormat(Formatter):
  38. def __init__(self, obj):
  39. self.data = obj
  40. self.timezone = None
  41. # We only support timezone when formatting datetime objects,
  42. # not date objects (timezone information not appropriate),
  43. # or time objects (against established django policy).
  44. if isinstance(obj, datetime.datetime):
  45. if is_naive(obj):
  46. self.timezone = get_default_timezone()
  47. else:
  48. self.timezone = obj.tzinfo
  49. def a(self):
  50. "'a.m.' or 'p.m.'"
  51. if self.data.hour > 11:
  52. return _('p.m.')
  53. return _('a.m.')
  54. def A(self):
  55. "'AM' or 'PM'"
  56. if self.data.hour > 11:
  57. return _('PM')
  58. return _('AM')
  59. def B(self):
  60. "Swatch Internet time"
  61. raise NotImplementedError('may be implemented in a future release')
  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. year_days = [None, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
  176. def b(self):
  177. "Month, textual, 3 letters, lowercase; e.g. 'jan'"
  178. return MONTHS_3[self.data.month]
  179. def c(self):
  180. """
  181. ISO 8601 Format
  182. Example : '2008-01-02T10:30:00.000123'
  183. """
  184. return self.data.isoformat()
  185. def d(self):
  186. "Day of the month, 2 digits with leading zeros; i.e. '01' to '31'"
  187. return '%02d' % self.data.day
  188. def D(self):
  189. "Day of the week, textual, 3 letters; e.g. 'Fri'"
  190. return WEEKDAYS_ABBR[self.data.weekday()]
  191. def E(self):
  192. "Alternative month names as required by some locales. Proprietary extension."
  193. return MONTHS_ALT[self.data.month]
  194. def F(self):
  195. "Month, textual, long; e.g. 'January'"
  196. return MONTHS[self.data.month]
  197. def I(self): # NOQA: E743
  198. "'1' if Daylight Savings Time, '0' otherwise."
  199. try:
  200. if self.timezone and self.timezone.dst(self.data):
  201. return '1'
  202. else:
  203. return '0'
  204. except Exception:
  205. # pytz raises AmbiguousTimeError during the autumn DST change.
  206. # This happens mainly when __init__ receives a naive datetime
  207. # and sets self.timezone = get_default_timezone().
  208. return ''
  209. def j(self):
  210. "Day of the month without leading zeros; i.e. '1' to '31'"
  211. return self.data.day
  212. def l(self): # NOQA: E743
  213. "Day of the week, textual, long; e.g. 'Friday'"
  214. return WEEKDAYS[self.data.weekday()]
  215. def L(self):
  216. "Boolean for whether it is a leap year; i.e. True or False"
  217. return calendar.isleap(self.data.year)
  218. def m(self):
  219. "Month; i.e. '01' to '12'"
  220. return '%02d' % self.data.month
  221. def M(self):
  222. "Month, textual, 3 letters; e.g. 'Jan'"
  223. return MONTHS_3[self.data.month].title()
  224. def n(self):
  225. "Month without leading zeros; i.e. '1' to '12'"
  226. return self.data.month
  227. def N(self):
  228. "Month abbreviation in Associated Press style. Proprietary extension."
  229. return MONTHS_AP[self.data.month]
  230. def o(self):
  231. "ISO 8601 year number matching the ISO week number (W)"
  232. return self.data.isocalendar()[0]
  233. def r(self):
  234. "RFC 5322 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'"
  235. return self.format('D, j M Y H:i:s O')
  236. def S(self):
  237. "English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th'"
  238. if self.data.day in (11, 12, 13): # Special case
  239. return 'th'
  240. last = self.data.day % 10
  241. if last == 1:
  242. return 'st'
  243. if last == 2:
  244. return 'nd'
  245. if last == 3:
  246. return 'rd'
  247. return 'th'
  248. def t(self):
  249. "Number of days in the given month; i.e. '28' to '31'"
  250. return '%02d' % calendar.monthrange(self.data.year, self.data.month)[1]
  251. def U(self):
  252. "Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)"
  253. if isinstance(self.data, datetime.datetime) and is_aware(self.data):
  254. return int(calendar.timegm(self.data.utctimetuple()))
  255. else:
  256. return int(time.mktime(self.data.timetuple()))
  257. def w(self):
  258. "Day of the week, numeric, i.e. '0' (Sunday) to '6' (Saturday)"
  259. return (self.data.weekday() + 1) % 7
  260. def W(self):
  261. "ISO-8601 week number of year, weeks starting on Monday"
  262. # Algorithm from http://www.personal.ecu.edu/mccartyr/ISOwdALG.txt
  263. jan1_weekday = self.data.replace(month=1, day=1).weekday() + 1
  264. weekday = self.data.weekday() + 1
  265. day_of_year = self.z()
  266. if day_of_year <= (8 - jan1_weekday) and jan1_weekday > 4:
  267. if jan1_weekday == 5 or (jan1_weekday == 6 and calendar.isleap(self.data.year - 1)):
  268. week_number = 53
  269. else:
  270. week_number = 52
  271. else:
  272. if calendar.isleap(self.data.year):
  273. i = 366
  274. else:
  275. i = 365
  276. if (i - day_of_year) < (4 - weekday):
  277. week_number = 1
  278. else:
  279. j = day_of_year + (7 - weekday) + (jan1_weekday - 1)
  280. week_number = j // 7
  281. if jan1_weekday > 4:
  282. week_number -= 1
  283. return week_number
  284. def y(self):
  285. "Year, 2 digits; e.g. '99'"
  286. return str(self.data.year)[2:]
  287. def Y(self):
  288. "Year, 4 digits; e.g. '1999'"
  289. return self.data.year
  290. def z(self):
  291. "Day of the year; i.e. '0' to '365'"
  292. doy = self.year_days[self.data.month] + self.data.day
  293. if self.L() and self.data.month > 2:
  294. doy += 1
  295. return doy
  296. def format(value, format_string):
  297. "Convenience function"
  298. df = DateFormat(value)
  299. return df.format(format_string)
  300. def time_format(value, format_string):
  301. "Convenience function"
  302. tf = TimeFormat(value)
  303. return tf.format(format_string)