dates.rst 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. .. -*- mode: rst; encoding: utf-8 -*-
  2. .. _date-and-time:
  3. =============
  4. Date and Time
  5. =============
  6. When working with date and time information in Python, you commonly use the
  7. classes ``date``, ``datetime`` and/or ``time`` from the `datetime` package.
  8. Babel provides functions for locale-specific formatting of those objects in its
  9. ``dates`` module:
  10. .. code-block:: pycon
  11. >>> from datetime import date, datetime, time
  12. >>> from babel.dates import format_date, format_datetime, format_time
  13. >>> d = date(2007, 4, 1)
  14. >>> format_date(d, locale='en')
  15. u'Apr 1, 2007'
  16. >>> format_date(d, locale='de_DE')
  17. u'01.04.2007'
  18. As this example demonstrates, Babel will automatically choose a date format
  19. that is appropriate for the requested locale.
  20. The ``format_*()`` functions also accept an optional ``format`` argument, which
  21. allows you to choose between one of four format variations:
  22. * ``short``,
  23. * ``medium`` (the default),
  24. * ``long``, and
  25. * ``full``.
  26. For example:
  27. .. code-block:: pycon
  28. >>> format_date(d, format='short', locale='en')
  29. u'4/1/07'
  30. >>> format_date(d, format='long', locale='en')
  31. u'April 1, 2007'
  32. >>> format_date(d, format='full', locale='en')
  33. u'Sunday, April 1, 2007'
  34. Core Time Concepts
  35. ==================
  36. Working with dates and time can be a complicated thing. Babel attempts to
  37. simplify working with them by making some decisions for you. Python's
  38. datetime module has different ways to deal with times and dates: naive and
  39. timezone-aware datetime objects.
  40. Babel generally recommends you to store all your time in naive datetime
  41. objects and treat them as UTC at all times. This simplifies dealing with
  42. time a lot because otherwise you can get into the hairy situation where
  43. you are dealing with datetime objects of different timezones. That is
  44. tricky because there are situations where time can be ambiguous. This is
  45. usually the case when dealing with dates around timezone transitions. The
  46. most common case of timezone transition is changes between daylight saving
  47. time and standard time.
  48. As such we recommend to always use UTC internally and only reformat to
  49. local time when returning dates to users. At that point the timezone the
  50. user has selected can usually be established and Babel can automatically
  51. rebase the time for you.
  52. To get the current time use the :meth:`~datetime.datetime.utcnow` method
  53. of the :class:`~datetime.datetime` object. It will return a naive
  54. :class:`~datetime.datetime` object in UTC.
  55. For more information about timezones see :ref:`timezone-support`.
  56. Pattern Syntax
  57. ==============
  58. While Babel makes it simple to use the appropriate date/time format for a given
  59. locale, you can also force it to use custom patterns. Note that Babel uses
  60. different patterns for specifying number and date formats compared to the
  61. Python equivalents (such as ``time.strftime()``), which have mostly been
  62. inherited from C and POSIX. The patterns used in Babel are based on the
  63. `Locale Data Markup Language specification`_ (LDML), which defines them as
  64. follows:
  65. A date/time pattern is a string of characters, where specific strings of
  66. characters are replaced with date and time data from a calendar when
  67. formatting or used to generate data for a calendar when parsing. […]
  68. Characters may be used multiple times. For example, if ``y`` is used for the
  69. year, ``yy`` might produce "99", whereas ``yyyy`` produces "1999". For most
  70. numerical fields, the number of characters specifies the field width. For
  71. example, if ``h`` is the hour, ``h`` might produce "5", but ``hh`` produces
  72. "05". For some characters, the count specifies whether an abbreviated or full
  73. form should be used […]
  74. Two single quotes represent a literal single quote, either inside or outside
  75. single quotes. Text within single quotes is not interpreted in any way (except
  76. for two adjacent single quotes).
  77. For example:
  78. .. code-block:: pycon
  79. >>> d = date(2007, 4, 1)
  80. >>> format_date(d, "EEE, MMM d, ''yy", locale='en')
  81. u"Sun, Apr 1, '07"
  82. >>> format_date(d, "EEEE, d.M.yyyy", locale='de')
  83. u'Sonntag, 1.4.2007'
  84. >>> t = time(15, 30)
  85. >>> format_time(t, "hh 'o''clock' a", locale='en')
  86. u"03 o'clock PM"
  87. >>> format_time(t, 'H:mm a', locale='de')
  88. u'15:30 nachm.'
  89. >>> dt = datetime(2007, 4, 1, 15, 30)
  90. >>> format_datetime(dt, "yyyyy.MMMM.dd GGG hh:mm a", locale='en')
  91. u'02007.April.01 AD 03:30 PM'
  92. The syntax for custom datetime format patterns is described in detail in the
  93. the `Locale Data Markup Language specification`_. The following table is just a
  94. relatively brief overview.
  95. .. _`Locale Data Markup Language specification`:
  96. http://unicode.org/reports/tr35/#Date_Format_Patterns
  97. Date Fields
  98. -----------
  99. +----------+--------+--------------------------------------------------------+
  100. | Field | Symbol | Description |
  101. +==========+========+========================================================+
  102. | Era | ``G`` | Replaced with the era string for the current date. One |
  103. | | | to three letters for the abbreviated form, four |
  104. | | | lettersfor the long form, five for the narrow form |
  105. +----------+--------+--------------------------------------------------------+
  106. | Year | ``y`` | Replaced by the year. Normally the length specifies |
  107. | | | the padding, but for two letters it also specifies the |
  108. | | | maximum length. |
  109. | +--------+--------------------------------------------------------+
  110. | | ``Y`` | Same as ``y`` but uses the ISO year-week calendar. ISO |
  111. | | | year-week increments after completing the last week of |
  112. | | | the year. Therefore it may change a few days before or |
  113. | | | after ``y``. Recommend use with the ``w`` Symbol. |
  114. | +--------+--------------------------------------------------------+
  115. | | ``u`` | ?? |
  116. +----------+--------+--------------------------------------------------------+
  117. | Quarter | ``Q`` | Use one or two for the numerical quarter, three for |
  118. | | | the abbreviation, or four for the full name. |
  119. | +--------+--------------------------------------------------------+
  120. | | ``q`` | Use one or two for the numerical quarter, three for |
  121. | | | the abbreviation, or four for the full name. |
  122. +----------+--------+--------------------------------------------------------+
  123. | Month | ``M`` | Use one or two for the numerical month, three for the |
  124. | | | abbreviation, or four for the full name, or five for |
  125. | | | the narrow name. |
  126. | +--------+--------------------------------------------------------+
  127. | | ``L`` | Use one or two for the numerical month, three for the |
  128. | | | abbreviation, or four for the full name, or 5 for the |
  129. | | | narrow name. |
  130. +----------+--------+--------------------------------------------------------+
  131. | Week | ``w`` | Week of year according to the ISO year-week calendar. |
  132. | | | This may have 52 or 53 weeks depending on the year. |
  133. | | | Recommend use with the ``Y`` symbol. |
  134. | +--------+--------------------------------------------------------+
  135. | | ``W`` | Week of month. |
  136. +----------+--------+--------------------------------------------------------+
  137. | Day | ``d`` | Day of month. |
  138. | +--------+--------------------------------------------------------+
  139. | | ``D`` | Day of year. |
  140. | +--------+--------------------------------------------------------+
  141. | | ``F`` | Day of week in month. |
  142. | +--------+--------------------------------------------------------+
  143. | | ``g`` | ?? |
  144. +----------+--------+--------------------------------------------------------+
  145. | Week day | ``E`` | Day of week. Use one through three letters for the |
  146. | | | short day, or four for the full name, or five for the |
  147. | | | narrow name. |
  148. | +--------+--------------------------------------------------------+
  149. | | ``e`` | Local day of week. Same as E except adds a numeric |
  150. | | | value that will depend on the local starting day of |
  151. | | | the week, using one or two letters. |
  152. | +--------+--------------------------------------------------------+
  153. | | ``c`` | ?? |
  154. +----------+--------+--------------------------------------------------------+
  155. Time Fields
  156. -----------
  157. +----------+--------+--------------------------------------------------------+
  158. | Field | Symbol | Description |
  159. +==========+========+========================================================+
  160. | Period | ``a`` | AM or PM |
  161. +----------+--------+--------------------------------------------------------+
  162. | Hour | ``h`` | Hour [1-12]. |
  163. | +--------+--------------------------------------------------------+
  164. | | ``H`` | Hour [0-23]. |
  165. | +--------+--------------------------------------------------------+
  166. | | ``K`` | Hour [0-11]. |
  167. | +--------+--------------------------------------------------------+
  168. | | ``k`` | Hour [1-24]. |
  169. +----------+--------+--------------------------------------------------------+
  170. | Minute | ``m`` | Use one or two for zero places padding. |
  171. +----------+--------+--------------------------------------------------------+
  172. | Second | ``s`` | Use one or two for zero places padding. |
  173. | +--------+--------------------------------------------------------+
  174. | | ``S`` | Fractional second, rounds to the count of letters. |
  175. | +--------+--------------------------------------------------------+
  176. | | ``A`` | Milliseconds in day. |
  177. +----------+--------+--------------------------------------------------------+
  178. | Timezone | ``z`` | Use one to three letters for the short timezone or |
  179. | | | four for the full name. |
  180. | +--------+--------------------------------------------------------+
  181. | | ``Z`` | Use one to three letters for RFC 822, four letters for |
  182. | | | GMT format. |
  183. | +--------+--------------------------------------------------------+
  184. | | ``v`` | Use one letter for short wall (generic) time, four for |
  185. | | | long wall time. |
  186. | +--------+--------------------------------------------------------+
  187. | | ``V`` | Same as ``z``, except that timezone abbreviations |
  188. | | | should be used regardless of whether they are in |
  189. | | | common use by the locale. |
  190. +----------+--------+--------------------------------------------------------+
  191. Time Delta Formatting
  192. =====================
  193. In addition to providing functions for formatting localized dates and times,
  194. the ``babel.dates`` module also provides a function to format the difference
  195. between two times, called a ''time delta''. These are usually represented as
  196. ``datetime.timedelta`` objects in Python, and it's also what you get when you
  197. subtract one ``datetime`` object from an other.
  198. The ``format_timedelta`` function takes a ``timedelta`` object and returns a
  199. human-readable representation. This happens at the cost of precision, as it
  200. chooses only the most significant unit (such as year, week, or hour) of the
  201. difference, and displays that:
  202. .. code-block:: pycon
  203. >>> from datetime import timedelta
  204. >>> from babel.dates import format_timedelta
  205. >>> delta = timedelta(days=6)
  206. >>> format_timedelta(delta, locale='en_US')
  207. u'1 week'
  208. The resulting strings are based from the CLDR data, and are properly
  209. pluralized depending on the plural rules of the locale and the calculated
  210. number of units.
  211. The function provides parameters for you to influence how this most significant
  212. unit is chosen: with ``threshold`` you set the value after which the
  213. presentation switches to the next larger unit, and with ``granularity`` you
  214. can limit the smallest unit to display:
  215. .. code-block:: pycon
  216. >>> delta = timedelta(days=6)
  217. >>> format_timedelta(delta, threshold=1.2, locale='en_US')
  218. u'6 days'
  219. >>> format_timedelta(delta, granularity='month', locale='en_US')
  220. u'1 month'
  221. .. _timezone-support:
  222. Time-zone Support
  223. =================
  224. Many of the verbose time formats include the time-zone, but time-zone
  225. information is not by default available for the Python ``datetime`` and
  226. ``time`` objects. The standard library includes only the abstract ``tzinfo``
  227. class, which you need appropriate implementations for to actually use in your
  228. application. Babel includes a ``tzinfo`` implementation for UTC (Universal
  229. Time).
  230. Babel uses `pytz`_ for real timezone support which includes the
  231. definitions of practically all of the time-zones used on the world, as
  232. well as important functions for reliably converting from UTC to local
  233. time, and vice versa. The module is generally wrapped for you so you can
  234. directly interface with it from within Babel:
  235. .. code-block:: pycon
  236. >>> from datetime import time
  237. >>> from babel.dates import get_timezone, UTC
  238. >>> dt = datetime(2007, 04, 01, 15, 30, tzinfo=UTC)
  239. >>> eastern = get_timezone('US/Eastern')
  240. >>> format_datetime(dt, 'H:mm Z', tzinfo=eastern, locale='en_US')
  241. u'11:30 -0400'
  242. The recommended approach to deal with different time-zones in a Python
  243. application is to always use UTC internally, and only convert from/to the users
  244. time-zone when accepting user input and displaying date/time data, respectively.
  245. You can use Babel together with ``pytz`` to apply a time-zone to any
  246. ``datetime`` or ``time`` object for display, leaving the original information
  247. unchanged:
  248. .. code-block:: pycon
  249. >>> british = get_timezone('Europe/London')
  250. >>> format_datetime(dt, 'H:mm zzzz', tzinfo=british, locale='en_US')
  251. u'16:30 British Summer Time'
  252. Here, the given UTC time is adjusted to the "Europe/London" time-zone, and
  253. daylight savings time is taken into account. Daylight savings time is also
  254. applied to ``format_time``, but because the actual date is unknown in that
  255. case, the current day is assumed to determine whether DST or standard time
  256. should be used.
  257. For many timezones it's also possible to ask for the next timezone
  258. transition. This for instance is useful to answer the question “when do I
  259. have to move the clock forward next”:
  260. .. code-block:: pycon
  261. >>> t = get_next_timezone_transition('Europe/Vienna', datetime(2011, 3, 2))
  262. >>> t
  263. <TimezoneTransition CET -> CEST (2011-03-27 01:00:00)>
  264. >>> t.from_offset
  265. 3600.0
  266. >>> t.to_offset
  267. 7200.0
  268. >>> t.from_tz
  269. 'CET'
  270. >>> t.to_tz
  271. 'CEST'
  272. Lastly Babel also provides support for working with the local timezone of
  273. your operating system. It's provided through the ``LOCALTZ`` constant:
  274. .. code-block:: pycon
  275. >>> from babel.dates import LOCALTZ, get_timezone_name
  276. >>> LOCALTZ
  277. <DstTzInfo 'Europe/Vienna' CET+1:00:00 STD>
  278. >>> get_timezone_name(LOCALTZ)
  279. u'Central European Time'
  280. .. _pytz: http://pytz.sourceforge.net/
  281. Localized Time-zone Names
  282. -------------------------
  283. While the ``Locale`` class provides access to various locale display names
  284. related to time-zones, the process of building a localized name of a time-zone
  285. is actually quite complicated. Babel implements it in separately usable
  286. functions in the ``babel.dates`` module, most importantly the
  287. ``get_timezone_name`` function:
  288. .. code-block:: pycon
  289. >>> from babel import Locale
  290. >>> from babel.dates import get_timezone_name, get_timezone
  291. >>> tz = get_timezone('Europe/Berlin')
  292. >>> get_timezone_name(tz, locale=Locale.parse('pt_PT'))
  293. u'Hora da Europa Central'
  294. You can pass the function either a ``datetime.tzinfo`` object, or a
  295. ``datetime.date`` or ``datetime.datetime`` object. If you pass an actual date,
  296. the function will be able to take daylight savings time into account. If you
  297. pass just the time-zone, Babel does not know whether daylight savings time is
  298. in effect, so it uses a generic representation, which is useful for example to
  299. display a list of time-zones to the user.
  300. .. code-block:: pycon
  301. >>> from datetime import datetime
  302. >>> dt = tz.localize(datetime(2007, 8, 15))
  303. >>> get_timezone_name(dt, locale=Locale.parse('de_DE'))
  304. u'Mitteleurop\xe4ische Sommerzeit'
  305. >>> get_timezone_name(tz, locale=Locale.parse('de_DE'))
  306. u'Mitteleurop\xe4ische Zeit'