dates.txt 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. .. -*- mode: rst; encoding: utf-8 -*-
  2. ===============
  3. Date Formatting
  4. ===============
  5. .. contents:: Contents
  6. :depth: 2
  7. .. sectnum::
  8. When working with date and time information in Python, you commonly use the
  9. classes ``date``, ``datetime`` and/or ``time`` from the `datetime`_ package.
  10. Babel provides functions for locale-specific formatting of those objects in its
  11. ``dates`` module:
  12. .. _`datetime`: http://docs.python.org/lib/module-datetime.html
  13. .. code-block:: pycon
  14. >>> from datetime import date, datetime, time
  15. >>> from babel.dates import format_date, format_datetime, format_time
  16. >>> d = date(2007, 4, 1)
  17. >>> format_date(d, locale='en')
  18. u'Apr 1, 2007'
  19. >>> format_date(d, locale='de_DE')
  20. u'01.04.2007'
  21. As this example demonstrates, Babel will automatically choose a date format
  22. that is appropriate for the requested locale.
  23. The ``format_*()`` functions also accept an optional ``format`` argument, which
  24. allows you to choose between one of four format variations:
  25. * ``short``,
  26. * ``medium`` (the default),
  27. * ``long``, and
  28. * ``full``.
  29. For example:
  30. .. code-block:: pycon
  31. >>> format_date(d, format='short', locale='en')
  32. u'4/1/07'
  33. >>> format_date(d, format='long', locale='en')
  34. u'April 1, 2007'
  35. >>> format_date(d, format='full', locale='en')
  36. u'Sunday, April 1, 2007'
  37. Pattern Syntax
  38. ==============
  39. While Babel makes it simple to use the appropriate date/time format for a given
  40. locale, you can also force it to use custom patterns. Note that Babel uses
  41. different patterns for specifying number and date formats compared to the
  42. Python equivalents (such as ``time.strftime()``), which have mostly been
  43. inherited from C and POSIX. The patterns used in Babel are based on the
  44. `Locale Data Markup Language specification`_ (LDML), which defines them as
  45. follows:
  46. A date/time pattern is a string of characters, where specific strings of
  47. characters are replaced with date and time data from a calendar when formatting
  48. or used to generate data for a calendar when parsing. […]
  49. Characters may be used multiple times. For example, if ``y`` is used for the
  50. year, ``yy`` might produce "99", whereas ``yyyy`` produces "1999". For most
  51. numerical fields, the number of characters specifies the field width. For
  52. example, if ``h`` is the hour, ``h`` might produce "5", but ``hh`` produces
  53. "05". For some characters, the count specifies whether an abbreviated or full
  54. form should be used […]
  55. Two single quotes represent a literal single quote, either inside or outside
  56. single quotes. Text within single quotes is not interpreted in any way (except
  57. for two adjacent single quotes).
  58. For example:
  59. .. code-block:: pycon
  60. >>> d = date(2007, 4, 1)
  61. >>> format_date(d, "EEE, MMM d, ''yy", locale='en')
  62. u"Sun, Apr 1, '07"
  63. >>> format_date(d, "EEEE, d.M.yyyy", locale='de')
  64. u'Sonntag, 1.4.2007'
  65. >>> t = time(15, 30)
  66. >>> format_time(t, "hh 'o''clock' a", locale='en')
  67. u"03 o'clock PM"
  68. >>> format_time(t, 'H:mm a', locale='de')
  69. u'15:30 nachm.'
  70. >>> dt = datetime(2007, 4, 1, 15, 30)
  71. >>> format_datetime(dt, "yyyyy.MMMM.dd GGG hh:mm a", locale='en')
  72. u'02007.April.01 AD 03:30 PM'
  73. The syntax for custom datetime format patterns is described in detail in the
  74. the `Locale Data Markup Language specification`_. The following table is just a
  75. relatively brief overview.
  76. .. _`Locale Data Markup Language specification`: http://unicode.org/reports/tr35/#Date_Format_Patterns
  77. Date Fields
  78. -----------
  79. +----------+--------+--------------------------------------------------------+
  80. | Field | Symbol | Description |
  81. +==========+========+========================================================+
  82. | Era | ``G`` | Replaced with the era string for the current date. One |
  83. | | | to three letters for the abbreviated form, four |
  84. | | | lettersfor the long form, five for the narrow form |
  85. +----------+--------+--------------------------------------------------------+
  86. | Year | ``y`` | Replaced by the year. Normally the length specifies |
  87. | | | the padding, but for two letters it also specifies the |
  88. | | | maximum length. |
  89. | +--------+--------------------------------------------------------+
  90. | | ``Y`` | Same as ``y`` but uses the ISO year-week calendar. |
  91. | +--------+--------------------------------------------------------+
  92. | | ``u`` | ?? |
  93. +----------+--------+--------------------------------------------------------+
  94. | Quarter | ``Q`` | Use one or two for the numerical quarter, three for |
  95. | | | the abbreviation, or four for the full name. |
  96. | +--------+--------------------------------------------------------+
  97. | | ``q`` | Use one or two for the numerical quarter, three for |
  98. | | | the abbreviation, or four for the full name. |
  99. +----------+--------+--------------------------------------------------------+
  100. | Month | ``M`` | Use one or two for the numerical month, three for the |
  101. | | | abbreviation, or four for the full name, or five for |
  102. | | | the narrow name. |
  103. | +--------+--------------------------------------------------------+
  104. | | ``L`` | Use one or two for the numerical month, three for the |
  105. | | | abbreviation, or four for the full name, or 5 for the |
  106. | | | narrow name. |
  107. +----------+--------+--------------------------------------------------------+
  108. | Week | ``w`` | Week of year. |
  109. | +--------+--------------------------------------------------------+
  110. | | ``W`` | Week of month. |
  111. +----------+--------+--------------------------------------------------------+
  112. | Day | ``d`` | Day of month. |
  113. | +--------+--------------------------------------------------------+
  114. | | ``D`` | Day of year. |
  115. | +--------+--------------------------------------------------------+
  116. | | ``F`` | Day of week in month. |
  117. | +--------+--------------------------------------------------------+
  118. | | ``g`` | ?? |
  119. +----------+--------+--------------------------------------------------------+
  120. | Week day | ``E`` | Day of week. Use one through three letters for the |
  121. | | | short day, or four for the full name, or five for the |
  122. | | | narrow name. |
  123. | +--------+--------------------------------------------------------+
  124. | | ``e`` | Local day of week. Same as E except adds a numeric |
  125. | | | value that will depend on the local starting day of |
  126. | | | the week, using one or two letters. |
  127. | +--------+--------------------------------------------------------+
  128. | | ``c`` | ?? |
  129. +----------+--------+--------------------------------------------------------+
  130. Time Fields
  131. -----------
  132. +----------+--------+--------------------------------------------------------+
  133. | Field | Symbol | Description |
  134. +==========+========+========================================================+
  135. | Period | ``a`` | AM or PM |
  136. +----------+--------+--------------------------------------------------------+
  137. | Hour | ``h`` | Hour [1-12]. |
  138. | +--------+--------------------------------------------------------+
  139. | | ``H`` | Hour [0-23]. |
  140. | +--------+--------------------------------------------------------+
  141. | | ``K`` | Hour [0-11]. |
  142. | +--------+--------------------------------------------------------+
  143. | | ``k`` | Hour [1-24]. |
  144. +----------+--------+--------------------------------------------------------+
  145. | Minute | ``m`` | Use one or two for zero places padding. |
  146. +----------+--------+--------------------------------------------------------+
  147. | Second | ``s`` | Use one or two for zero places padding. |
  148. | +--------+--------------------------------------------------------+
  149. | | ``S`` | Fractional second, rounds to the count of letters. |
  150. | +--------+--------------------------------------------------------+
  151. | | ``A`` | Milliseconds in day. |
  152. +----------+--------+--------------------------------------------------------+
  153. | Timezone | ``z`` | Use one to three letters for the short timezone or |
  154. | | | four for the full name. |
  155. | +--------+--------------------------------------------------------+
  156. | | ``Z`` | Use one to three letters for RFC 822, four letters for |
  157. | | | GMT format. |
  158. | +--------+--------------------------------------------------------+
  159. | | ``v`` | Use one letter for short wall (generic) time, four for |
  160. | | | long wall time. |
  161. | +--------+--------------------------------------------------------+
  162. | | ``V`` | Same as ``z``, except that timezone abbreviations |
  163. | | | should be used regardless of whether they are in |
  164. | | | common use by the locale. |
  165. +----------+--------+--------------------------------------------------------+
  166. Time-zone Support
  167. =================
  168. Many of the verbose time formats include the time-zone, but time-zone
  169. information is not by default available for the Python ``datetime`` and
  170. ``time`` objects. The standard library includes only the abstract ``tzinfo``
  171. class, which you need appropriate implementations for to actually use in your
  172. application. Babel includes a ``tzinfo`` implementation for UTC (Universal
  173. Time).
  174. For real time-zone support, it is strongly recommended that you use the
  175. third-party package `pytz`_, which includes the definitions of practically all
  176. of the time-zones used on the world, as well as important functions for
  177. reliably converting from UTC to local time, and vice versa:
  178. .. code-block:: pycon
  179. >>> from datetime import time
  180. >>> from pytz import timezone, utc
  181. >>> dt = datetime(2007, 04, 01, 15, 30, tzinfo=utc)
  182. >>> eastern = timezone('US/Eastern')
  183. >>> format_datetime(dt, 'H:mm Z', tzinfo=eastern, locale='en_US')
  184. u'11:30 -0400'
  185. The recommended approach to deal with different time-zones in a Python
  186. application is to always use UTC internally, and only convert from/to the users
  187. time-zone when accepting user input and displaying date/time data, respectively.
  188. You can use Babel together with ``pytz`` to apply a time-zone to any
  189. ``datetime`` or ``time`` object for display, leaving the original information
  190. unchanged:
  191. .. code-block:: pycon
  192. >>> british = timezone('Europe/London')
  193. >>> format_datetime(dt, 'H:mm zzzz', tzinfo=british, locale='en_US')
  194. u'16:30 British Summer Time'
  195. Here, the given UTC time is adjusted to the "Europe/London" time-zone, and
  196. daylight savings time is taken into account. Daylight savings time is also
  197. applied to ``format_time``, but because the actual date is unknown in that
  198. case, the current day is assumed to determine whether DST or standard time
  199. should be used.
  200. .. _`pytz`: http://pytz.sourceforge.net/
  201. Localized Time-zone Names
  202. -------------------------
  203. While the ``Locale`` class provides access to various locale display names
  204. related to time-zones, the process of building a localized name of a time-zone
  205. is actually quite complicated. Babel implements it in separately usable
  206. functions in the ``babel.dates`` module, most importantly the
  207. ``get_timezone_name`` function:
  208. .. code-block:: pycon
  209. >>> from pytz import timezone
  210. >>> from babel import Locale
  211. >>> from babel.dates import get_timezone_name
  212. >>> tz = timezone('Europe/Berlin')
  213. >>> get_timezone_name(tz, locale=Locale.parse('pt_PT'))
  214. u'Hor\xe1rio Alemanha'
  215. You can pass the function either a ``datetime.tzinfo`` object, or a
  216. ``datetime.date`` or ``datetime.datetime`` object. If you pass an actual date,
  217. the function will be able to take daylight savings time into account. If you
  218. pass just the time-zone, Babel does not know whether daylight savings time is
  219. in effect, so it uses a generic representation, which is useful for example to
  220. display a list of time-zones to the user.
  221. .. code-block:: pycon
  222. >>> from datetime import datetime
  223. >>> dt = tz.localize(datetime(2007, 8, 15))
  224. >>> get_timezone_name(dt, locale=Locale.parse('de_DE'))
  225. u'Mitteleurop\xe4ische Sommerzeit'
  226. >>> get_timezone_name(tz, locale=Locale.parse('de_DE'))
  227. u'Deutschland'
  228. Parsing Dates
  229. =============
  230. Babel can also parse date and time information in a locale-sensitive manner:
  231. .. code-block:: pycon
  232. >>> from babel.dates import parse_date, parse_datetime, parse_time
  233. .. note:: Date/time parsing is not properly implemented yet