dateformat.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. from __future__ import unicode_literals
  13. import calendar
  14. import datetime
  15. import re
  16. import time
  17. from django.utils import six
  18. from django.utils.dates import (
  19. MONTHS, MONTHS_3, MONTHS_ALT, MONTHS_AP, WEEKDAYS, WEEKDAYS_ABBR,
  20. )
  21. from django.utils.encoding import force_text
  22. from django.utils.timezone import get_default_timezone, is_aware, is_naive
  23. from django.utils.translation import ugettext as _
  24. re_formatchars = re.compile(r'(?<!\\)([aAbBcdDeEfFgGhHiIjlLmMnNoOPrsStTUuwWyYzZ])')
  25. re_escaped = re.compile(r'\\(.)')
  26. class Formatter(object):
  27. def format(self, formatstr):
  28. pieces = []
  29. for i, piece in enumerate(re_formatchars.split(force_text(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(force_text(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 B(self):
  63. "Swatch Internet time"
  64. raise NotImplementedError('may be implemented in a future release')
  65. def e(self):
  66. """
  67. Timezone name.
  68. If timezone information is not available, this method returns
  69. an empty string.
  70. """
  71. if not self.timezone:
  72. return ""
  73. try:
  74. if hasattr(self.data, 'tzinfo') and self.data.tzinfo:
  75. # Have to use tzinfo.tzname and not datetime.tzname
  76. # because datatime.tzname does not expect Unicode
  77. return self.data.tzinfo.tzname(self.data) or ""
  78. except NotImplementedError:
  79. pass
  80. return ""
  81. def f(self):
  82. """
  83. Time, in 12-hour hours and minutes, with minutes left off if they're
  84. zero.
  85. Examples: '1', '1:30', '2:05', '2'
  86. Proprietary extension.
  87. """
  88. if self.data.minute == 0:
  89. return self.g()
  90. return '%s:%s' % (self.g(), self.i())
  91. def g(self):
  92. "Hour, 12-hour format without leading zeros; i.e. '1' to '12'"
  93. if self.data.hour == 0:
  94. return 12
  95. if self.data.hour > 12:
  96. return self.data.hour - 12
  97. return self.data.hour
  98. def G(self):
  99. "Hour, 24-hour format without leading zeros; i.e. '0' to '23'"
  100. return self.data.hour
  101. def h(self):
  102. "Hour, 12-hour format; i.e. '01' to '12'"
  103. return '%02d' % self.g()
  104. def H(self):
  105. "Hour, 24-hour format; i.e. '00' to '23'"
  106. return '%02d' % self.G()
  107. def i(self):
  108. "Minutes; i.e. '00' to '59'"
  109. return '%02d' % self.data.minute
  110. def O(self): # NOQA: E743
  111. """
  112. Difference to Greenwich time in hours; e.g. '+0200', '-0430'.
  113. If timezone information is not available, this method returns
  114. an empty string.
  115. """
  116. if not self.timezone:
  117. return ""
  118. seconds = self.Z()
  119. if seconds == "":
  120. return ""
  121. sign = '-' if seconds < 0 else '+'
  122. seconds = abs(seconds)
  123. return "%s%02d%02d" % (sign, seconds // 3600, (seconds // 60) % 60)
  124. def P(self):
  125. """
  126. Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off
  127. if they're zero and the strings 'midnight' and 'noon' if appropriate.
  128. Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.'
  129. Proprietary extension.
  130. """
  131. if self.data.minute == 0 and self.data.hour == 0:
  132. return _('midnight')
  133. if self.data.minute == 0 and self.data.hour == 12:
  134. return _('noon')
  135. return '%s %s' % (self.f(), self.a())
  136. def s(self):
  137. "Seconds; i.e. '00' to '59'"
  138. return '%02d' % self.data.second
  139. def T(self):
  140. """
  141. Time zone of this machine; e.g. 'EST' or 'MDT'.
  142. If timezone information is not available, this method returns
  143. an empty string.
  144. """
  145. if not self.timezone:
  146. return ""
  147. name = None
  148. try:
  149. name = self.timezone.tzname(self.data)
  150. except Exception:
  151. # pytz raises AmbiguousTimeError during the autumn DST change.
  152. # This happens mainly when __init__ receives a naive datetime
  153. # and sets self.timezone = get_default_timezone().
  154. pass
  155. if name is None:
  156. name = self.format('O')
  157. return six.text_type(name)
  158. def u(self):
  159. "Microseconds; i.e. '000000' to '999999'"
  160. return '%06d' % self.data.microsecond
  161. def Z(self):
  162. """
  163. Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for
  164. timezones west of UTC is always negative, and for those east of UTC is
  165. always positive.
  166. If timezone information is not available, this method returns
  167. an empty string.
  168. """
  169. if not self.timezone:
  170. return ""
  171. try:
  172. offset = self.timezone.utcoffset(self.data)
  173. except Exception:
  174. # pytz raises AmbiguousTimeError during the autumn DST change.
  175. # This happens mainly when __init__ receives a naive datetime
  176. # and sets self.timezone = get_default_timezone().
  177. return ""
  178. # `offset` is a datetime.timedelta. For negative values (to the west of
  179. # UTC) only days can be negative (days=-1) and seconds are always
  180. # positive. e.g. UTC-1 -> timedelta(days=-1, seconds=82800, microseconds=0)
  181. # Positive offsets have days=0
  182. return offset.days * 86400 + offset.seconds
  183. class DateFormat(TimeFormat):
  184. year_days = [None, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
  185. def b(self):
  186. "Month, textual, 3 letters, lowercase; e.g. 'jan'"
  187. return MONTHS_3[self.data.month]
  188. def c(self):
  189. """
  190. ISO 8601 Format
  191. Example : '2008-01-02T10:30:00.000123'
  192. """
  193. return self.data.isoformat()
  194. def d(self):
  195. "Day of the month, 2 digits with leading zeros; i.e. '01' to '31'"
  196. return '%02d' % self.data.day
  197. def D(self):
  198. "Day of the week, textual, 3 letters; e.g. 'Fri'"
  199. return WEEKDAYS_ABBR[self.data.weekday()]
  200. def E(self):
  201. "Alternative month names as required by some locales. Proprietary extension."
  202. return MONTHS_ALT[self.data.month]
  203. def F(self):
  204. "Month, textual, long; e.g. 'January'"
  205. return MONTHS[self.data.month]
  206. def I(self): # NOQA: E743
  207. "'1' if Daylight Savings Time, '0' otherwise."
  208. try:
  209. if self.timezone and self.timezone.dst(self.data):
  210. return '1'
  211. else:
  212. return '0'
  213. except Exception:
  214. # pytz raises AmbiguousTimeError during the autumn DST change.
  215. # This happens mainly when __init__ receives a naive datetime
  216. # and sets self.timezone = get_default_timezone().
  217. return ''
  218. def j(self):
  219. "Day of the month without leading zeros; i.e. '1' to '31'"
  220. return self.data.day
  221. def l(self): # NOQA: E743
  222. "Day of the week, textual, long; e.g. 'Friday'"
  223. return WEEKDAYS[self.data.weekday()]
  224. def L(self):
  225. "Boolean for whether it is a leap year; i.e. True or False"
  226. return calendar.isleap(self.data.year)
  227. def m(self):
  228. "Month; i.e. '01' to '12'"
  229. return '%02d' % self.data.month
  230. def M(self):
  231. "Month, textual, 3 letters; e.g. 'Jan'"
  232. return MONTHS_3[self.data.month].title()
  233. def n(self):
  234. "Month without leading zeros; i.e. '1' to '12'"
  235. return self.data.month
  236. def N(self):
  237. "Month abbreviation in Associated Press style. Proprietary extension."
  238. return MONTHS_AP[self.data.month]
  239. def o(self):
  240. "ISO 8601 year number matching the ISO week number (W)"
  241. return self.data.isocalendar()[0]
  242. def r(self):
  243. "RFC 5322 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'"
  244. return self.format('D, j M Y H:i:s O')
  245. def S(self):
  246. "English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th'"
  247. if self.data.day in (11, 12, 13): # Special case
  248. return 'th'
  249. last = self.data.day % 10
  250. if last == 1:
  251. return 'st'
  252. if last == 2:
  253. return 'nd'
  254. if last == 3:
  255. return 'rd'
  256. return 'th'
  257. def t(self):
  258. "Number of days in the given month; i.e. '28' to '31'"
  259. return '%02d' % calendar.monthrange(self.data.year, self.data.month)[1]
  260. def U(self):
  261. "Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)"
  262. if isinstance(self.data, datetime.datetime) and is_aware(self.data):
  263. return int(calendar.timegm(self.data.utctimetuple()))
  264. else:
  265. return int(time.mktime(self.data.timetuple()))
  266. def w(self):
  267. "Day of the week, numeric, i.e. '0' (Sunday) to '6' (Saturday)"
  268. return (self.data.weekday() + 1) % 7
  269. def W(self):
  270. "ISO-8601 week number of year, weeks starting on Monday"
  271. # Algorithm from http://www.personal.ecu.edu/mccartyr/ISOwdALG.txt
  272. week_number = None
  273. jan1_weekday = self.data.replace(month=1, day=1).weekday() + 1
  274. weekday = self.data.weekday() + 1
  275. day_of_year = self.z()
  276. if day_of_year <= (8 - jan1_weekday) and jan1_weekday > 4:
  277. if jan1_weekday == 5 or (jan1_weekday == 6 and calendar.isleap(self.data.year - 1)):
  278. week_number = 53
  279. else:
  280. week_number = 52
  281. else:
  282. if calendar.isleap(self.data.year):
  283. i = 366
  284. else:
  285. i = 365
  286. if (i - day_of_year) < (4 - weekday):
  287. week_number = 1
  288. else:
  289. j = day_of_year + (7 - weekday) + (jan1_weekday - 1)
  290. week_number = j // 7
  291. if jan1_weekday > 4:
  292. week_number -= 1
  293. return week_number
  294. def y(self):
  295. "Year, 2 digits; e.g. '99'"
  296. return six.text_type(self.data.year)[2:]
  297. def Y(self):
  298. "Year, 4 digits; e.g. '1999'"
  299. return self.data.year
  300. def z(self):
  301. "Day of the year; i.e. '0' to '365'"
  302. doy = self.year_days[self.data.month] + self.data.day
  303. if self.L() and self.data.month > 2:
  304. doy += 1
  305. return doy
  306. def format(value, format_string):
  307. "Convenience function"
  308. df = DateFormat(value)
  309. return df.format(format_string)
  310. def time_format(value, format_string):
  311. "Convenience function"
  312. tf = TimeFormat(value)
  313. return tf.format(format_string)