dates.py 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758
  1. # -*- coding: utf-8 -*-
  2. """
  3. babel.dates
  4. ~~~~~~~~~~~
  5. Locale dependent formatting and parsing of dates and times.
  6. The default locale for the functions in this module is determined by the
  7. following environment variables, in that order:
  8. * ``LC_TIME``,
  9. * ``LC_ALL``, and
  10. * ``LANG``
  11. :copyright: (c) 2013 by the Babel Team.
  12. :license: BSD, see LICENSE for more details.
  13. """
  14. from __future__ import division
  15. import re
  16. import warnings
  17. import pytz as _pytz
  18. from datetime import date, datetime, time, timedelta
  19. from bisect import bisect_right
  20. from babel.core import default_locale, get_global, Locale
  21. from babel.util import UTC, LOCALTZ
  22. from babel._compat import string_types, integer_types, number_types
  23. LC_TIME = default_locale('LC_TIME')
  24. # Aliases for use in scopes where the modules are shadowed by local variables
  25. date_ = date
  26. datetime_ = datetime
  27. time_ = time
  28. def _get_dt_and_tzinfo(dt_or_tzinfo):
  29. """
  30. Parse a `dt_or_tzinfo` value into a datetime and a tzinfo.
  31. See the docs for this function's callers for semantics.
  32. :rtype: tuple[datetime, tzinfo]
  33. """
  34. if dt_or_tzinfo is None:
  35. dt = datetime.now()
  36. tzinfo = LOCALTZ
  37. elif isinstance(dt_or_tzinfo, string_types):
  38. dt = None
  39. tzinfo = get_timezone(dt_or_tzinfo)
  40. elif isinstance(dt_or_tzinfo, integer_types):
  41. dt = None
  42. tzinfo = UTC
  43. elif isinstance(dt_or_tzinfo, (datetime, time)):
  44. dt = _get_datetime(dt_or_tzinfo)
  45. if dt.tzinfo is not None:
  46. tzinfo = dt.tzinfo
  47. else:
  48. tzinfo = UTC
  49. else:
  50. dt = None
  51. tzinfo = dt_or_tzinfo
  52. return dt, tzinfo
  53. def _get_datetime(instant):
  54. """
  55. Get a datetime out of an "instant" (date, time, datetime, number).
  56. .. warning:: The return values of this function may depend on the system clock.
  57. If the instant is None, the current moment is used.
  58. If the instant is a time, it's augmented with today's date.
  59. Dates are converted to naive datetimes with midnight as the time component.
  60. >>> _get_datetime(date(2015, 1, 1))
  61. datetime.datetime(2015, 1, 1, 0, 0)
  62. UNIX timestamps are converted to datetimes.
  63. >>> _get_datetime(1400000000)
  64. datetime.datetime(2014, 5, 13, 16, 53, 20)
  65. Other values are passed through as-is.
  66. >>> x = datetime(2015, 1, 1)
  67. >>> _get_datetime(x) is x
  68. True
  69. :param instant: date, time, datetime, integer, float or None
  70. :type instant: date|time|datetime|int|float|None
  71. :return: a datetime
  72. :rtype: datetime
  73. """
  74. if instant is None:
  75. return datetime_.utcnow()
  76. elif isinstance(instant, integer_types) or isinstance(instant, float):
  77. return datetime_.utcfromtimestamp(instant)
  78. elif isinstance(instant, time):
  79. return datetime_.combine(date.today(), instant)
  80. elif isinstance(instant, date) and not isinstance(instant, datetime):
  81. return datetime_.combine(instant, time())
  82. # TODO (3.x): Add an assertion/type check for this fallthrough branch:
  83. return instant
  84. def _ensure_datetime_tzinfo(datetime, tzinfo=None):
  85. """
  86. Ensure the datetime passed has an attached tzinfo.
  87. If the datetime is tz-naive to begin with, UTC is attached.
  88. If a tzinfo is passed in, the datetime is normalized to that timezone.
  89. >>> _ensure_datetime_tzinfo(datetime(2015, 1, 1)).tzinfo.zone
  90. 'UTC'
  91. >>> tz = get_timezone("Europe/Stockholm")
  92. >>> _ensure_datetime_tzinfo(datetime(2015, 1, 1, 13, 15, tzinfo=UTC), tzinfo=tz).hour
  93. 14
  94. :param datetime: Datetime to augment.
  95. :param tzinfo: Optional tznfo.
  96. :return: datetime with tzinfo
  97. :rtype: datetime
  98. """
  99. if datetime.tzinfo is None:
  100. datetime = datetime.replace(tzinfo=UTC)
  101. if tzinfo is not None:
  102. datetime = datetime.astimezone(get_timezone(tzinfo))
  103. if hasattr(tzinfo, 'normalize'): # pytz
  104. datetime = tzinfo.normalize(datetime)
  105. return datetime
  106. def _get_time(time, tzinfo=None):
  107. """
  108. Get a timezoned time from a given instant.
  109. .. warning:: The return values of this function may depend on the system clock.
  110. :param time: time, datetime or None
  111. :rtype: time
  112. """
  113. if time is None:
  114. time = datetime.utcnow()
  115. elif isinstance(time, number_types):
  116. time = datetime.utcfromtimestamp(time)
  117. if time.tzinfo is None:
  118. time = time.replace(tzinfo=UTC)
  119. if isinstance(time, datetime):
  120. if tzinfo is not None:
  121. time = time.astimezone(tzinfo)
  122. if hasattr(tzinfo, 'normalize'): # pytz
  123. time = tzinfo.normalize(time)
  124. time = time.timetz()
  125. elif tzinfo is not None:
  126. time = time.replace(tzinfo=tzinfo)
  127. return time
  128. def get_timezone(zone=None):
  129. """Looks up a timezone by name and returns it. The timezone object
  130. returned comes from ``pytz`` and corresponds to the `tzinfo` interface and
  131. can be used with all of the functions of Babel that operate with dates.
  132. If a timezone is not known a :exc:`LookupError` is raised. If `zone`
  133. is ``None`` a local zone object is returned.
  134. :param zone: the name of the timezone to look up. If a timezone object
  135. itself is passed in, mit's returned unchanged.
  136. """
  137. if zone is None:
  138. return LOCALTZ
  139. if not isinstance(zone, string_types):
  140. return zone
  141. try:
  142. return _pytz.timezone(zone)
  143. except _pytz.UnknownTimeZoneError:
  144. raise LookupError('Unknown timezone %s' % zone)
  145. def get_next_timezone_transition(zone=None, dt=None):
  146. """Given a timezone it will return a :class:`TimezoneTransition` object
  147. that holds the information about the next timezone transition that's going
  148. to happen. For instance this can be used to detect when the next DST
  149. change is going to happen and how it looks like.
  150. The transition is calculated relative to the given datetime object. The
  151. next transition that follows the date is used. If a transition cannot
  152. be found the return value will be `None`.
  153. Transition information can only be provided for timezones returned by
  154. the :func:`get_timezone` function.
  155. :param zone: the timezone for which the transition should be looked up.
  156. If not provided the local timezone is used.
  157. :param dt: the date after which the next transition should be found.
  158. If not given the current time is assumed.
  159. """
  160. zone = get_timezone(zone)
  161. dt = _get_datetime(dt).replace(tzinfo=None)
  162. if not hasattr(zone, '_utc_transition_times'):
  163. raise TypeError('Given timezone does not have UTC transition '
  164. 'times. This can happen because the operating '
  165. 'system fallback local timezone is used or a '
  166. 'custom timezone object')
  167. try:
  168. idx = max(0, bisect_right(zone._utc_transition_times, dt))
  169. old_trans = zone._transition_info[idx - 1]
  170. new_trans = zone._transition_info[idx]
  171. old_tz = zone._tzinfos[old_trans]
  172. new_tz = zone._tzinfos[new_trans]
  173. except (LookupError, ValueError):
  174. return None
  175. return TimezoneTransition(
  176. activates=zone._utc_transition_times[idx],
  177. from_tzinfo=old_tz,
  178. to_tzinfo=new_tz,
  179. reference_date=dt
  180. )
  181. class TimezoneTransition(object):
  182. """A helper object that represents the return value from
  183. :func:`get_next_timezone_transition`.
  184. """
  185. def __init__(self, activates, from_tzinfo, to_tzinfo, reference_date=None):
  186. #: the time of the activation of the timezone transition in UTC.
  187. self.activates = activates
  188. #: the timezone from where the transition starts.
  189. self.from_tzinfo = from_tzinfo
  190. #: the timezone for after the transition.
  191. self.to_tzinfo = to_tzinfo
  192. #: the reference date that was provided. This is the `dt` parameter
  193. #: to the :func:`get_next_timezone_transition`.
  194. self.reference_date = reference_date
  195. @property
  196. def from_tz(self):
  197. """The name of the timezone before the transition."""
  198. return self.from_tzinfo._tzname
  199. @property
  200. def to_tz(self):
  201. """The name of the timezone after the transition."""
  202. return self.to_tzinfo._tzname
  203. @property
  204. def from_offset(self):
  205. """The UTC offset in seconds before the transition."""
  206. return int(self.from_tzinfo._utcoffset.total_seconds())
  207. @property
  208. def to_offset(self):
  209. """The UTC offset in seconds after the transition."""
  210. return int(self.to_tzinfo._utcoffset.total_seconds())
  211. def __repr__(self):
  212. return '<TimezoneTransition %s -> %s (%s)>' % (
  213. self.from_tz,
  214. self.to_tz,
  215. self.activates,
  216. )
  217. def get_period_names(width='wide', context='stand-alone', locale=LC_TIME):
  218. """Return the names for day periods (AM/PM) used by the locale.
  219. >>> get_period_names(locale='en_US')['am']
  220. u'AM'
  221. :param width: the width to use, one of "abbreviated", "narrow", or "wide"
  222. :param context: the context, either "format" or "stand-alone"
  223. :param locale: the `Locale` object, or a locale string
  224. """
  225. return Locale.parse(locale).day_periods[context][width]
  226. def get_day_names(width='wide', context='format', locale=LC_TIME):
  227. """Return the day names used by the locale for the specified format.
  228. >>> get_day_names('wide', locale='en_US')[1]
  229. u'Tuesday'
  230. >>> get_day_names('short', locale='en_US')[1]
  231. u'Tu'
  232. >>> get_day_names('abbreviated', locale='es')[1]
  233. u'mar.'
  234. >>> get_day_names('narrow', context='stand-alone', locale='de_DE')[1]
  235. u'D'
  236. :param width: the width to use, one of "wide", "abbreviated", "short" or "narrow"
  237. :param context: the context, either "format" or "stand-alone"
  238. :param locale: the `Locale` object, or a locale string
  239. """
  240. return Locale.parse(locale).days[context][width]
  241. def get_month_names(width='wide', context='format', locale=LC_TIME):
  242. """Return the month names used by the locale for the specified format.
  243. >>> get_month_names('wide', locale='en_US')[1]
  244. u'January'
  245. >>> get_month_names('abbreviated', locale='es')[1]
  246. u'ene.'
  247. >>> get_month_names('narrow', context='stand-alone', locale='de_DE')[1]
  248. u'J'
  249. :param width: the width to use, one of "wide", "abbreviated", or "narrow"
  250. :param context: the context, either "format" or "stand-alone"
  251. :param locale: the `Locale` object, or a locale string
  252. """
  253. return Locale.parse(locale).months[context][width]
  254. def get_quarter_names(width='wide', context='format', locale=LC_TIME):
  255. """Return the quarter names used by the locale for the specified format.
  256. >>> get_quarter_names('wide', locale='en_US')[1]
  257. u'1st quarter'
  258. >>> get_quarter_names('abbreviated', locale='de_DE')[1]
  259. u'Q1'
  260. >>> get_quarter_names('narrow', locale='de_DE')[1]
  261. u'1'
  262. :param width: the width to use, one of "wide", "abbreviated", or "narrow"
  263. :param context: the context, either "format" or "stand-alone"
  264. :param locale: the `Locale` object, or a locale string
  265. """
  266. return Locale.parse(locale).quarters[context][width]
  267. def get_era_names(width='wide', locale=LC_TIME):
  268. """Return the era names used by the locale for the specified format.
  269. >>> get_era_names('wide', locale='en_US')[1]
  270. u'Anno Domini'
  271. >>> get_era_names('abbreviated', locale='de_DE')[1]
  272. u'n. Chr.'
  273. :param width: the width to use, either "wide", "abbreviated", or "narrow"
  274. :param locale: the `Locale` object, or a locale string
  275. """
  276. return Locale.parse(locale).eras[width]
  277. def get_date_format(format='medium', locale=LC_TIME):
  278. """Return the date formatting patterns used by the locale for the specified
  279. format.
  280. >>> get_date_format(locale='en_US')
  281. <DateTimePattern u'MMM d, y'>
  282. >>> get_date_format('full', locale='de_DE')
  283. <DateTimePattern u'EEEE, d. MMMM y'>
  284. :param format: the format to use, one of "full", "long", "medium", or
  285. "short"
  286. :param locale: the `Locale` object, or a locale string
  287. """
  288. return Locale.parse(locale).date_formats[format]
  289. def get_datetime_format(format='medium', locale=LC_TIME):
  290. """Return the datetime formatting patterns used by the locale for the
  291. specified format.
  292. >>> get_datetime_format(locale='en_US')
  293. u'{1}, {0}'
  294. :param format: the format to use, one of "full", "long", "medium", or
  295. "short"
  296. :param locale: the `Locale` object, or a locale string
  297. """
  298. patterns = Locale.parse(locale).datetime_formats
  299. if format not in patterns:
  300. format = None
  301. return patterns[format]
  302. def get_time_format(format='medium', locale=LC_TIME):
  303. """Return the time formatting patterns used by the locale for the specified
  304. format.
  305. >>> get_time_format(locale='en_US')
  306. <DateTimePattern u'h:mm:ss a'>
  307. >>> get_time_format('full', locale='de_DE')
  308. <DateTimePattern u'HH:mm:ss zzzz'>
  309. :param format: the format to use, one of "full", "long", "medium", or
  310. "short"
  311. :param locale: the `Locale` object, or a locale string
  312. """
  313. return Locale.parse(locale).time_formats[format]
  314. def get_timezone_gmt(datetime=None, width='long', locale=LC_TIME, return_z=False):
  315. """Return the timezone associated with the given `datetime` object formatted
  316. as string indicating the offset from GMT.
  317. >>> dt = datetime(2007, 4, 1, 15, 30)
  318. >>> get_timezone_gmt(dt, locale='en')
  319. u'GMT+00:00'
  320. >>> get_timezone_gmt(dt, locale='en', return_z=True)
  321. 'Z'
  322. >>> get_timezone_gmt(dt, locale='en', width='iso8601_short')
  323. u'+00'
  324. >>> tz = get_timezone('America/Los_Angeles')
  325. >>> dt = tz.localize(datetime(2007, 4, 1, 15, 30))
  326. >>> get_timezone_gmt(dt, locale='en')
  327. u'GMT-07:00'
  328. >>> get_timezone_gmt(dt, 'short', locale='en')
  329. u'-0700'
  330. >>> get_timezone_gmt(dt, locale='en', width='iso8601_short')
  331. u'-07'
  332. The long format depends on the locale, for example in France the acronym
  333. UTC string is used instead of GMT:
  334. >>> get_timezone_gmt(dt, 'long', locale='fr_FR')
  335. u'UTC-07:00'
  336. .. versionadded:: 0.9
  337. :param datetime: the ``datetime`` object; if `None`, the current date and
  338. time in UTC is used
  339. :param width: either "long" or "short" or "iso8601" or "iso8601_short"
  340. :param locale: the `Locale` object, or a locale string
  341. :param return_z: True or False; Function returns indicator "Z"
  342. when local time offset is 0
  343. """
  344. datetime = _ensure_datetime_tzinfo(_get_datetime(datetime))
  345. locale = Locale.parse(locale)
  346. offset = datetime.tzinfo.utcoffset(datetime)
  347. seconds = offset.days * 24 * 60 * 60 + offset.seconds
  348. hours, seconds = divmod(seconds, 3600)
  349. if return_z and hours == 0 and seconds == 0:
  350. return 'Z'
  351. elif seconds == 0 and width == 'iso8601_short':
  352. return u'%+03d' % hours
  353. elif width == 'short' or width == 'iso8601_short':
  354. pattern = u'%+03d%02d'
  355. elif width == 'iso8601':
  356. pattern = u'%+03d:%02d'
  357. else:
  358. pattern = locale.zone_formats['gmt'] % '%+03d:%02d'
  359. return pattern % (hours, seconds // 60)
  360. def get_timezone_location(dt_or_tzinfo=None, locale=LC_TIME, return_city=False):
  361. u"""Return a representation of the given timezone using "location format".
  362. The result depends on both the local display name of the country and the
  363. city associated with the time zone:
  364. >>> tz = get_timezone('America/St_Johns')
  365. >>> print(get_timezone_location(tz, locale='de_DE'))
  366. Kanada (St. John’s) Zeit
  367. >>> print(get_timezone_location(tz, locale='en'))
  368. Canada (St. John’s) Time
  369. >>> print(get_timezone_location(tz, locale='en', return_city=True))
  370. St. John’s
  371. >>> tz = get_timezone('America/Mexico_City')
  372. >>> get_timezone_location(tz, locale='de_DE')
  373. u'Mexiko (Mexiko-Stadt) Zeit'
  374. If the timezone is associated with a country that uses only a single
  375. timezone, just the localized country name is returned:
  376. >>> tz = get_timezone('Europe/Berlin')
  377. >>> get_timezone_name(tz, locale='de_DE')
  378. u'Mitteleurop\\xe4ische Zeit'
  379. .. versionadded:: 0.9
  380. :param dt_or_tzinfo: the ``datetime`` or ``tzinfo`` object that determines
  381. the timezone; if `None`, the current date and time in
  382. UTC is assumed
  383. :param locale: the `Locale` object, or a locale string
  384. :param return_city: True or False, if True then return exemplar city (location)
  385. for the time zone
  386. :return: the localized timezone name using location format
  387. """
  388. dt, tzinfo = _get_dt_and_tzinfo(dt_or_tzinfo)
  389. locale = Locale.parse(locale)
  390. if hasattr(tzinfo, 'zone'):
  391. zone = tzinfo.zone
  392. else:
  393. zone = tzinfo.tzname(dt or datetime.utcnow())
  394. # Get the canonical time-zone code
  395. zone = get_global('zone_aliases').get(zone, zone)
  396. info = locale.time_zones.get(zone, {})
  397. # Otherwise, if there is only one timezone for the country, return the
  398. # localized country name
  399. region_format = locale.zone_formats['region']
  400. territory = get_global('zone_territories').get(zone)
  401. if territory not in locale.territories:
  402. territory = 'ZZ' # invalid/unknown
  403. territory_name = locale.territories[territory]
  404. if not return_city and territory and len(get_global('territory_zones').get(territory, [])) == 1:
  405. return region_format % (territory_name)
  406. # Otherwise, include the city in the output
  407. fallback_format = locale.zone_formats['fallback']
  408. if 'city' in info:
  409. city_name = info['city']
  410. else:
  411. metazone = get_global('meta_zones').get(zone)
  412. metazone_info = locale.meta_zones.get(metazone, {})
  413. if 'city' in metazone_info:
  414. city_name = metazone_info['city']
  415. elif '/' in zone:
  416. city_name = zone.split('/', 1)[1].replace('_', ' ')
  417. else:
  418. city_name = zone.replace('_', ' ')
  419. if return_city:
  420. return city_name
  421. return region_format % (fallback_format % {
  422. '0': city_name,
  423. '1': territory_name
  424. })
  425. def get_timezone_name(dt_or_tzinfo=None, width='long', uncommon=False,
  426. locale=LC_TIME, zone_variant=None, return_zone=False):
  427. r"""Return the localized display name for the given timezone. The timezone
  428. may be specified using a ``datetime`` or `tzinfo` object.
  429. >>> dt = time(15, 30, tzinfo=get_timezone('America/Los_Angeles'))
  430. >>> get_timezone_name(dt, locale='en_US')
  431. u'Pacific Standard Time'
  432. >>> get_timezone_name(dt, locale='en_US', return_zone=True)
  433. 'America/Los_Angeles'
  434. >>> get_timezone_name(dt, width='short', locale='en_US')
  435. u'PST'
  436. If this function gets passed only a `tzinfo` object and no concrete
  437. `datetime`, the returned display name is indenpendent of daylight savings
  438. time. This can be used for example for selecting timezones, or to set the
  439. time of events that recur across DST changes:
  440. >>> tz = get_timezone('America/Los_Angeles')
  441. >>> get_timezone_name(tz, locale='en_US')
  442. u'Pacific Time'
  443. >>> get_timezone_name(tz, 'short', locale='en_US')
  444. u'PT'
  445. If no localized display name for the timezone is available, and the timezone
  446. is associated with a country that uses only a single timezone, the name of
  447. that country is returned, formatted according to the locale:
  448. >>> tz = get_timezone('Europe/Berlin')
  449. >>> get_timezone_name(tz, locale='de_DE')
  450. u'Mitteleurop\xe4ische Zeit'
  451. >>> get_timezone_name(tz, locale='pt_BR')
  452. u'Hor\xe1rio da Europa Central'
  453. On the other hand, if the country uses multiple timezones, the city is also
  454. included in the representation:
  455. >>> tz = get_timezone('America/St_Johns')
  456. >>> get_timezone_name(tz, locale='de_DE')
  457. u'Neufundland-Zeit'
  458. Note that short format is currently not supported for all timezones and
  459. all locales. This is partially because not every timezone has a short
  460. code in every locale. In that case it currently falls back to the long
  461. format.
  462. For more information see `LDML Appendix J: Time Zone Display Names
  463. <http://www.unicode.org/reports/tr35/#Time_Zone_Fallback>`_
  464. .. versionadded:: 0.9
  465. .. versionchanged:: 1.0
  466. Added `zone_variant` support.
  467. :param dt_or_tzinfo: the ``datetime`` or ``tzinfo`` object that determines
  468. the timezone; if a ``tzinfo`` object is used, the
  469. resulting display name will be generic, i.e.
  470. independent of daylight savings time; if `None`, the
  471. current date in UTC is assumed
  472. :param width: either "long" or "short"
  473. :param uncommon: deprecated and ignored
  474. :param zone_variant: defines the zone variation to return. By default the
  475. variation is defined from the datetime object
  476. passed in. If no datetime object is passed in, the
  477. ``'generic'`` variation is assumed. The following
  478. values are valid: ``'generic'``, ``'daylight'`` and
  479. ``'standard'``.
  480. :param locale: the `Locale` object, or a locale string
  481. :param return_zone: True or False. If true then function
  482. returns long time zone ID
  483. """
  484. dt, tzinfo = _get_dt_and_tzinfo(dt_or_tzinfo)
  485. locale = Locale.parse(locale)
  486. if hasattr(tzinfo, 'zone'):
  487. zone = tzinfo.zone
  488. else:
  489. zone = tzinfo.tzname(dt)
  490. if zone_variant is None:
  491. if dt is None:
  492. zone_variant = 'generic'
  493. else:
  494. dst = tzinfo.dst(dt)
  495. if dst:
  496. zone_variant = 'daylight'
  497. else:
  498. zone_variant = 'standard'
  499. else:
  500. if zone_variant not in ('generic', 'standard', 'daylight'):
  501. raise ValueError('Invalid zone variation')
  502. # Get the canonical time-zone code
  503. zone = get_global('zone_aliases').get(zone, zone)
  504. if return_zone:
  505. return zone
  506. info = locale.time_zones.get(zone, {})
  507. # Try explicitly translated zone names first
  508. if width in info:
  509. if zone_variant in info[width]:
  510. return info[width][zone_variant]
  511. metazone = get_global('meta_zones').get(zone)
  512. if metazone:
  513. metazone_info = locale.meta_zones.get(metazone, {})
  514. if width in metazone_info:
  515. if zone_variant in metazone_info[width]:
  516. return metazone_info[width][zone_variant]
  517. # If we have a concrete datetime, we assume that the result can't be
  518. # independent of daylight savings time, so we return the GMT offset
  519. if dt is not None:
  520. return get_timezone_gmt(dt, width=width, locale=locale)
  521. return get_timezone_location(dt_or_tzinfo, locale=locale)
  522. def format_date(date=None, format='medium', locale=LC_TIME):
  523. """Return a date formatted according to the given pattern.
  524. >>> d = date(2007, 4, 1)
  525. >>> format_date(d, locale='en_US')
  526. u'Apr 1, 2007'
  527. >>> format_date(d, format='full', locale='de_DE')
  528. u'Sonntag, 1. April 2007'
  529. If you don't want to use the locale default formats, you can specify a
  530. custom date pattern:
  531. >>> format_date(d, "EEE, MMM d, ''yy", locale='en')
  532. u"Sun, Apr 1, '07"
  533. :param date: the ``date`` or ``datetime`` object; if `None`, the current
  534. date is used
  535. :param format: one of "full", "long", "medium", or "short", or a custom
  536. date/time pattern
  537. :param locale: a `Locale` object or a locale identifier
  538. """
  539. if date is None:
  540. date = date_.today()
  541. elif isinstance(date, datetime):
  542. date = date.date()
  543. locale = Locale.parse(locale)
  544. if format in ('full', 'long', 'medium', 'short'):
  545. format = get_date_format(format, locale=locale)
  546. pattern = parse_pattern(format)
  547. return pattern.apply(date, locale)
  548. def format_datetime(datetime=None, format='medium', tzinfo=None,
  549. locale=LC_TIME):
  550. r"""Return a date formatted according to the given pattern.
  551. >>> dt = datetime(2007, 4, 1, 15, 30)
  552. >>> format_datetime(dt, locale='en_US')
  553. u'Apr 1, 2007, 3:30:00 PM'
  554. For any pattern requiring the display of the time-zone, the third-party
  555. ``pytz`` package is needed to explicitly specify the time-zone:
  556. >>> format_datetime(dt, 'full', tzinfo=get_timezone('Europe/Paris'),
  557. ... locale='fr_FR')
  558. u'dimanche 1 avril 2007 \xe0 17:30:00 heure d\u2019\xe9t\xe9 d\u2019Europe centrale'
  559. >>> format_datetime(dt, "yyyy.MM.dd G 'at' HH:mm:ss zzz",
  560. ... tzinfo=get_timezone('US/Eastern'), locale='en')
  561. u'2007.04.01 AD at 11:30:00 EDT'
  562. :param datetime: the `datetime` object; if `None`, the current date and
  563. time is used
  564. :param format: one of "full", "long", "medium", or "short", or a custom
  565. date/time pattern
  566. :param tzinfo: the timezone to apply to the time for display
  567. :param locale: a `Locale` object or a locale identifier
  568. """
  569. datetime = _ensure_datetime_tzinfo(_get_datetime(datetime), tzinfo)
  570. locale = Locale.parse(locale)
  571. if format in ('full', 'long', 'medium', 'short'):
  572. return get_datetime_format(format, locale=locale) \
  573. .replace("'", "") \
  574. .replace('{0}', format_time(datetime, format, tzinfo=None,
  575. locale=locale)) \
  576. .replace('{1}', format_date(datetime, format, locale=locale))
  577. else:
  578. return parse_pattern(format).apply(datetime, locale)
  579. def format_time(time=None, format='medium', tzinfo=None, locale=LC_TIME):
  580. r"""Return a time formatted according to the given pattern.
  581. >>> t = time(15, 30)
  582. >>> format_time(t, locale='en_US')
  583. u'3:30:00 PM'
  584. >>> format_time(t, format='short', locale='de_DE')
  585. u'15:30'
  586. If you don't want to use the locale default formats, you can specify a
  587. custom time pattern:
  588. >>> format_time(t, "hh 'o''clock' a", locale='en')
  589. u"03 o'clock PM"
  590. For any pattern requiring the display of the time-zone a
  591. timezone has to be specified explicitly:
  592. >>> t = datetime(2007, 4, 1, 15, 30)
  593. >>> tzinfo = get_timezone('Europe/Paris')
  594. >>> t = tzinfo.localize(t)
  595. >>> format_time(t, format='full', tzinfo=tzinfo, locale='fr_FR')
  596. u'15:30:00 heure d\u2019\xe9t\xe9 d\u2019Europe centrale'
  597. >>> format_time(t, "hh 'o''clock' a, zzzz", tzinfo=get_timezone('US/Eastern'),
  598. ... locale='en')
  599. u"09 o'clock AM, Eastern Daylight Time"
  600. As that example shows, when this function gets passed a
  601. ``datetime.datetime`` value, the actual time in the formatted string is
  602. adjusted to the timezone specified by the `tzinfo` parameter. If the
  603. ``datetime`` is "naive" (i.e. it has no associated timezone information),
  604. it is assumed to be in UTC.
  605. These timezone calculations are **not** performed if the value is of type
  606. ``datetime.time``, as without date information there's no way to determine
  607. what a given time would translate to in a different timezone without
  608. information about whether daylight savings time is in effect or not. This
  609. means that time values are left as-is, and the value of the `tzinfo`
  610. parameter is only used to display the timezone name if needed:
  611. >>> t = time(15, 30)
  612. >>> format_time(t, format='full', tzinfo=get_timezone('Europe/Paris'),
  613. ... locale='fr_FR')
  614. u'15:30:00 heure normale d\u2019Europe centrale'
  615. >>> format_time(t, format='full', tzinfo=get_timezone('US/Eastern'),
  616. ... locale='en_US')
  617. u'3:30:00 PM Eastern Standard Time'
  618. :param time: the ``time`` or ``datetime`` object; if `None`, the current
  619. time in UTC is used
  620. :param format: one of "full", "long", "medium", or "short", or a custom
  621. date/time pattern
  622. :param tzinfo: the time-zone to apply to the time for display
  623. :param locale: a `Locale` object or a locale identifier
  624. """
  625. time = _get_time(time, tzinfo)
  626. locale = Locale.parse(locale)
  627. if format in ('full', 'long', 'medium', 'short'):
  628. format = get_time_format(format, locale=locale)
  629. return parse_pattern(format).apply(time, locale)
  630. def format_skeleton(skeleton, datetime=None, tzinfo=None, fuzzy=True, locale=LC_TIME):
  631. r"""Return a time and/or date formatted according to the given pattern.
  632. The skeletons are defined in the CLDR data and provide more flexibility
  633. than the simple short/long/medium formats, but are a bit harder to use.
  634. The are defined using the date/time symbols without order or punctuation
  635. and map to a suitable format for the given locale.
  636. >>> t = datetime(2007, 4, 1, 15, 30)
  637. >>> format_skeleton('MMMEd', t, locale='fr')
  638. u'dim. 1 avr.'
  639. >>> format_skeleton('MMMEd', t, locale='en')
  640. u'Sun, Apr 1'
  641. >>> format_skeleton('yMMd', t, locale='fi') # yMMd is not in the Finnish locale; yMd gets used
  642. u'1.4.2007'
  643. >>> format_skeleton('yMMd', t, fuzzy=False, locale='fi') # yMMd is not in the Finnish locale, an error is thrown
  644. Traceback (most recent call last):
  645. ...
  646. KeyError: yMMd
  647. After the skeleton is resolved to a pattern `format_datetime` is called so
  648. all timezone processing etc is the same as for that.
  649. :param skeleton: A date time skeleton as defined in the cldr data.
  650. :param datetime: the ``time`` or ``datetime`` object; if `None`, the current
  651. time in UTC is used
  652. :param tzinfo: the time-zone to apply to the time for display
  653. :param fuzzy: If the skeleton is not found, allow choosing a skeleton that's
  654. close enough to it.
  655. :param locale: a `Locale` object or a locale identifier
  656. """
  657. locale = Locale.parse(locale)
  658. if fuzzy and skeleton not in locale.datetime_skeletons:
  659. skeleton = match_skeleton(skeleton, locale.datetime_skeletons)
  660. format = locale.datetime_skeletons[skeleton]
  661. return format_datetime(datetime, format, tzinfo, locale)
  662. TIMEDELTA_UNITS = (
  663. ('year', 3600 * 24 * 365),
  664. ('month', 3600 * 24 * 30),
  665. ('week', 3600 * 24 * 7),
  666. ('day', 3600 * 24),
  667. ('hour', 3600),
  668. ('minute', 60),
  669. ('second', 1)
  670. )
  671. def format_timedelta(delta, granularity='second', threshold=.85,
  672. add_direction=False, format='long',
  673. locale=LC_TIME):
  674. """Return a time delta according to the rules of the given locale.
  675. >>> format_timedelta(timedelta(weeks=12), locale='en_US')
  676. u'3 months'
  677. >>> format_timedelta(timedelta(seconds=1), locale='es')
  678. u'1 segundo'
  679. The granularity parameter can be provided to alter the lowest unit
  680. presented, which defaults to a second.
  681. >>> format_timedelta(timedelta(hours=3), granularity='day',
  682. ... locale='en_US')
  683. u'1 day'
  684. The threshold parameter can be used to determine at which value the
  685. presentation switches to the next higher unit. A higher threshold factor
  686. means the presentation will switch later. For example:
  687. >>> format_timedelta(timedelta(hours=23), threshold=0.9, locale='en_US')
  688. u'1 day'
  689. >>> format_timedelta(timedelta(hours=23), threshold=1.1, locale='en_US')
  690. u'23 hours'
  691. In addition directional information can be provided that informs
  692. the user if the date is in the past or in the future:
  693. >>> format_timedelta(timedelta(hours=1), add_direction=True, locale='en')
  694. u'in 1 hour'
  695. >>> format_timedelta(timedelta(hours=-1), add_direction=True, locale='en')
  696. u'1 hour ago'
  697. The format parameter controls how compact or wide the presentation is:
  698. >>> format_timedelta(timedelta(hours=3), format='short', locale='en')
  699. u'3 hr'
  700. >>> format_timedelta(timedelta(hours=3), format='narrow', locale='en')
  701. u'3h'
  702. :param delta: a ``timedelta`` object representing the time difference to
  703. format, or the delta in seconds as an `int` value
  704. :param granularity: determines the smallest unit that should be displayed,
  705. the value can be one of "year", "month", "week", "day",
  706. "hour", "minute" or "second"
  707. :param threshold: factor that determines at which point the presentation
  708. switches to the next higher unit
  709. :param add_direction: if this flag is set to `True` the return value will
  710. include directional information. For instance a
  711. positive timedelta will include the information about
  712. it being in the future, a negative will be information
  713. about the value being in the past.
  714. :param format: the format, can be "narrow", "short" or "long". (
  715. "medium" is deprecated, currently converted to "long" to
  716. maintain compatibility)
  717. :param locale: a `Locale` object or a locale identifier
  718. """
  719. if format not in ('narrow', 'short', 'medium', 'long'):
  720. raise TypeError('Format must be one of "narrow", "short" or "long"')
  721. if format == 'medium':
  722. warnings.warn('"medium" value for format param of format_timedelta'
  723. ' is deprecated. Use "long" instead',
  724. category=DeprecationWarning)
  725. format = 'long'
  726. if isinstance(delta, timedelta):
  727. seconds = int((delta.days * 86400) + delta.seconds)
  728. else:
  729. seconds = delta
  730. locale = Locale.parse(locale)
  731. def _iter_patterns(a_unit):
  732. if add_direction:
  733. unit_rel_patterns = locale._data['date_fields'][a_unit]
  734. if seconds >= 0:
  735. yield unit_rel_patterns['future']
  736. else:
  737. yield unit_rel_patterns['past']
  738. a_unit = 'duration-' + a_unit
  739. yield locale._data['unit_patterns'].get(a_unit, {}).get(format)
  740. for unit, secs_per_unit in TIMEDELTA_UNITS:
  741. value = abs(seconds) / secs_per_unit
  742. if value >= threshold or unit == granularity:
  743. if unit == granularity and value > 0:
  744. value = max(1, value)
  745. value = int(round(value))
  746. plural_form = locale.plural_form(value)
  747. pattern = None
  748. for patterns in _iter_patterns(unit):
  749. if patterns is not None:
  750. pattern = patterns[plural_form]
  751. break
  752. # This really should not happen
  753. if pattern is None:
  754. return u''
  755. return pattern.replace('{0}', str(value))
  756. return u''
  757. def _format_fallback_interval(start, end, skeleton, tzinfo, locale):
  758. if skeleton in locale.datetime_skeletons: # Use the given skeleton
  759. format = lambda dt: format_skeleton(skeleton, dt, tzinfo, locale=locale)
  760. elif all((isinstance(d, date) and not isinstance(d, datetime)) for d in (start, end)): # Both are just dates
  761. format = lambda dt: format_date(dt, locale=locale)
  762. elif all((isinstance(d, time) and not isinstance(d, date)) for d in (start, end)): # Both are times
  763. format = lambda dt: format_time(dt, tzinfo=tzinfo, locale=locale)
  764. else:
  765. format = lambda dt: format_datetime(dt, tzinfo=tzinfo, locale=locale)
  766. formatted_start = format(start)
  767. formatted_end = format(end)
  768. if formatted_start == formatted_end:
  769. return format(start)
  770. return (
  771. locale.interval_formats.get(None, "{0}-{1}").
  772. replace("{0}", formatted_start).
  773. replace("{1}", formatted_end)
  774. )
  775. def format_interval(start, end, skeleton=None, tzinfo=None, fuzzy=True, locale=LC_TIME):
  776. """
  777. Format an interval between two instants according to the locale's rules.
  778. >>> format_interval(date(2016, 1, 15), date(2016, 1, 17), "yMd", locale="fi")
  779. u'15.\u201317.1.2016'
  780. >>> format_interval(time(12, 12), time(16, 16), "Hm", locale="en_GB")
  781. '12:12 \u2013 16:16'
  782. >>> format_interval(time(5, 12), time(16, 16), "hm", locale="en_US")
  783. '5:12 AM \u2013 4:16 PM'
  784. >>> format_interval(time(16, 18), time(16, 24), "Hm", locale="it")
  785. '16:18\u201316:24'
  786. If the start instant equals the end instant, the interval is formatted like the instant.
  787. >>> format_interval(time(16, 18), time(16, 18), "Hm", locale="it")
  788. '16:18'
  789. Unknown skeletons fall back to "default" formatting.
  790. >>> format_interval(date(2015, 1, 1), date(2017, 1, 1), "wzq", locale="ja")
  791. '2015/01/01\uff5e2017/01/01'
  792. >>> format_interval(time(16, 18), time(16, 24), "xxx", locale="ja")
  793. '16:18:00\uff5e16:24:00'
  794. >>> format_interval(date(2016, 1, 15), date(2016, 1, 17), "xxx", locale="de")
  795. '15.01.2016 \u2013 17.01.2016'
  796. :param start: First instant (datetime/date/time)
  797. :param end: Second instant (datetime/date/time)
  798. :param skeleton: The "skeleton format" to use for formatting.
  799. :param tzinfo: tzinfo to use (if none is already attached)
  800. :param fuzzy: If the skeleton is not found, allow choosing a skeleton that's
  801. close enough to it.
  802. :param locale: A locale object or identifier.
  803. :return: Formatted interval
  804. """
  805. locale = Locale.parse(locale)
  806. # NB: The quote comments below are from the algorithm description in
  807. # http://www.unicode.org/reports/tr35/tr35-dates.html#intervalFormats
  808. # > Look for the intervalFormatItem element that matches the "skeleton",
  809. # > starting in the current locale and then following the locale fallback
  810. # > chain up to, but not including root.
  811. interval_formats = locale.interval_formats
  812. if skeleton not in interval_formats or not skeleton:
  813. # > If no match was found from the previous step, check what the closest
  814. # > match is in the fallback locale chain, as in availableFormats. That
  815. # > is, this allows for adjusting the string value field's width,
  816. # > including adjusting between "MMM" and "MMMM", and using different
  817. # > variants of the same field, such as 'v' and 'z'.
  818. if skeleton and fuzzy:
  819. skeleton = match_skeleton(skeleton, interval_formats)
  820. else:
  821. skeleton = None
  822. if not skeleton: # Still no match whatsoever?
  823. # > Otherwise, format the start and end datetime using the fallback pattern.
  824. return _format_fallback_interval(start, end, skeleton, tzinfo, locale)
  825. skel_formats = interval_formats[skeleton]
  826. if start == end:
  827. return format_skeleton(skeleton, start, tzinfo, fuzzy=fuzzy, locale=locale)
  828. start = _ensure_datetime_tzinfo(_get_datetime(start), tzinfo=tzinfo)
  829. end = _ensure_datetime_tzinfo(_get_datetime(end), tzinfo=tzinfo)
  830. start_fmt = DateTimeFormat(start, locale=locale)
  831. end_fmt = DateTimeFormat(end, locale=locale)
  832. # > If a match is found from previous steps, compute the calendar field
  833. # > with the greatest difference between start and end datetime. If there
  834. # > is no difference among any of the fields in the pattern, format as a
  835. # > single date using availableFormats, and return.
  836. for field in PATTERN_CHAR_ORDER: # These are in largest-to-smallest order
  837. if field in skel_formats:
  838. if start_fmt.extract(field) != end_fmt.extract(field):
  839. # > If there is a match, use the pieces of the corresponding pattern to
  840. # > format the start and end datetime, as above.
  841. return "".join(
  842. parse_pattern(pattern).apply(instant, locale)
  843. for pattern, instant
  844. in zip(skel_formats[field], (start, end))
  845. )
  846. # > Otherwise, format the start and end datetime using the fallback pattern.
  847. return _format_fallback_interval(start, end, skeleton, tzinfo, locale)
  848. def get_period_id(time, tzinfo=None, type=None, locale=LC_TIME):
  849. """
  850. Get the day period ID for a given time.
  851. This ID can be used as a key for the period name dictionary.
  852. >>> get_period_names(locale="de")[get_period_id(time(7, 42), locale="de")]
  853. u'Morgen'
  854. :param time: The time to inspect.
  855. :param tzinfo: The timezone for the time. See ``format_time``.
  856. :param type: The period type to use. Either "selection" or None.
  857. The selection type is used for selecting among phrases such as
  858. “Your email arrived yesterday evening” or “Your email arrived last night”.
  859. :param locale: the `Locale` object, or a locale string
  860. :return: period ID. Something is always returned -- even if it's just "am" or "pm".
  861. """
  862. time = _get_time(time, tzinfo)
  863. seconds_past_midnight = int(time.hour * 60 * 60 + time.minute * 60 + time.second)
  864. locale = Locale.parse(locale)
  865. # The LDML rules state that the rules may not overlap, so iterating in arbitrary
  866. # order should be alright, though `at` periods should be preferred.
  867. rulesets = locale.day_period_rules.get(type, {}).items()
  868. for rule_id, rules in rulesets:
  869. for rule in rules:
  870. if "at" in rule and rule["at"] == seconds_past_midnight:
  871. return rule_id
  872. for rule_id, rules in rulesets:
  873. for rule in rules:
  874. start_ok = end_ok = False
  875. if "from" in rule and seconds_past_midnight >= rule["from"]:
  876. start_ok = True
  877. if "to" in rule and seconds_past_midnight <= rule["to"]:
  878. # This rule type does not exist in the present CLDR data;
  879. # excuse the lack of test coverage.
  880. end_ok = True
  881. if "before" in rule and seconds_past_midnight < rule["before"]:
  882. end_ok = True
  883. if "after" in rule:
  884. raise NotImplementedError("'after' is deprecated as of CLDR 29.")
  885. if start_ok and end_ok:
  886. return rule_id
  887. if seconds_past_midnight < 43200:
  888. return "am"
  889. else:
  890. return "pm"
  891. def parse_date(string, locale=LC_TIME):
  892. """Parse a date from a string.
  893. This function uses the date format for the locale as a hint to determine
  894. the order in which the date fields appear in the string.
  895. >>> parse_date('4/1/04', locale='en_US')
  896. datetime.date(2004, 4, 1)
  897. >>> parse_date('01.04.2004', locale='de_DE')
  898. datetime.date(2004, 4, 1)
  899. :param string: the string containing the date
  900. :param locale: a `Locale` object or a locale identifier
  901. """
  902. # TODO: try ISO format first?
  903. format = get_date_format(locale=locale).pattern.lower()
  904. year_idx = format.index('y')
  905. month_idx = format.index('m')
  906. if month_idx < 0:
  907. month_idx = format.index('l')
  908. day_idx = format.index('d')
  909. indexes = [(year_idx, 'Y'), (month_idx, 'M'), (day_idx, 'D')]
  910. indexes.sort()
  911. indexes = dict([(item[1], idx) for idx, item in enumerate(indexes)])
  912. # FIXME: this currently only supports numbers, but should also support month
  913. # names, both in the requested locale, and english
  914. numbers = re.findall('(\d+)', string)
  915. year = numbers[indexes['Y']]
  916. if len(year) == 2:
  917. year = 2000 + int(year)
  918. else:
  919. year = int(year)
  920. month = int(numbers[indexes['M']])
  921. day = int(numbers[indexes['D']])
  922. if month > 12:
  923. month, day = day, month
  924. return date(year, month, day)
  925. def parse_time(string, locale=LC_TIME):
  926. """Parse a time from a string.
  927. This function uses the time format for the locale as a hint to determine
  928. the order in which the time fields appear in the string.
  929. >>> parse_time('15:30:00', locale='en_US')
  930. datetime.time(15, 30)
  931. :param string: the string containing the time
  932. :param locale: a `Locale` object or a locale identifier
  933. :return: the parsed time
  934. :rtype: `time`
  935. """
  936. # TODO: try ISO format first?
  937. format = get_time_format(locale=locale).pattern.lower()
  938. hour_idx = format.index('h')
  939. if hour_idx < 0:
  940. hour_idx = format.index('k')
  941. min_idx = format.index('m')
  942. sec_idx = format.index('s')
  943. indexes = [(hour_idx, 'H'), (min_idx, 'M'), (sec_idx, 'S')]
  944. indexes.sort()
  945. indexes = dict([(item[1], idx) for idx, item in enumerate(indexes)])
  946. # FIXME: support 12 hour clock, and 0-based hour specification
  947. # and seconds should be optional, maybe minutes too
  948. # oh, and time-zones, of course
  949. numbers = re.findall('(\d+)', string)
  950. hour = int(numbers[indexes['H']])
  951. minute = int(numbers[indexes['M']])
  952. second = int(numbers[indexes['S']])
  953. return time(hour, minute, second)
  954. class DateTimePattern(object):
  955. def __init__(self, pattern, format):
  956. self.pattern = pattern
  957. self.format = format
  958. def __repr__(self):
  959. return '<%s %r>' % (type(self).__name__, self.pattern)
  960. def __unicode__(self):
  961. return self.pattern
  962. def __mod__(self, other):
  963. if type(other) is not DateTimeFormat:
  964. return NotImplemented
  965. return self.format % other
  966. def apply(self, datetime, locale):
  967. return self % DateTimeFormat(datetime, locale)
  968. class DateTimeFormat(object):
  969. def __init__(self, value, locale):
  970. assert isinstance(value, (date, datetime, time))
  971. if isinstance(value, (datetime, time)) and value.tzinfo is None:
  972. value = value.replace(tzinfo=UTC)
  973. self.value = value
  974. self.locale = Locale.parse(locale)
  975. def __getitem__(self, name):
  976. char = name[0]
  977. num = len(name)
  978. if char == 'G':
  979. return self.format_era(char, num)
  980. elif char in ('y', 'Y', 'u'):
  981. return self.format_year(char, num)
  982. elif char in ('Q', 'q'):
  983. return self.format_quarter(char, num)
  984. elif char in ('M', 'L'):
  985. return self.format_month(char, num)
  986. elif char in ('w', 'W'):
  987. return self.format_week(char, num)
  988. elif char == 'd':
  989. return self.format(self.value.day, num)
  990. elif char == 'D':
  991. return self.format_day_of_year(num)
  992. elif char == 'F':
  993. return self.format_day_of_week_in_month()
  994. elif char in ('E', 'e', 'c'):
  995. return self.format_weekday(char, num)
  996. elif char == 'a':
  997. # TODO: Add support for the rest of the period formats (a*, b*, B*)
  998. return self.format_period(char)
  999. elif char == 'h':
  1000. if self.value.hour % 12 == 0:
  1001. return self.format(12, num)
  1002. else:
  1003. return self.format(self.value.hour % 12, num)
  1004. elif char == 'H':
  1005. return self.format(self.value.hour, num)
  1006. elif char == 'K':
  1007. return self.format(self.value.hour % 12, num)
  1008. elif char == 'k':
  1009. if self.value.hour == 0:
  1010. return self.format(24, num)
  1011. else:
  1012. return self.format(self.value.hour, num)
  1013. elif char == 'm':
  1014. return self.format(self.value.minute, num)
  1015. elif char == 's':
  1016. return self.format(self.value.second, num)
  1017. elif char == 'S':
  1018. return self.format_frac_seconds(num)
  1019. elif char == 'A':
  1020. return self.format_milliseconds_in_day(num)
  1021. elif char in ('z', 'Z', 'v', 'V', 'x', 'X', 'O'):
  1022. return self.format_timezone(char, num)
  1023. else:
  1024. raise KeyError('Unsupported date/time field %r' % char)
  1025. def extract(self, char):
  1026. char = str(char)[0]
  1027. if char == 'y':
  1028. return self.value.year
  1029. elif char == 'M':
  1030. return self.value.month
  1031. elif char == 'd':
  1032. return self.value.day
  1033. elif char == 'H':
  1034. return self.value.hour
  1035. elif char == 'h':
  1036. return (self.value.hour % 12 or 12)
  1037. elif char == 'm':
  1038. return self.value.minute
  1039. elif char == 'a':
  1040. return int(self.value.hour >= 12) # 0 for am, 1 for pm
  1041. else:
  1042. raise NotImplementedError("Not implemented: extracting %r from %r" % (char, self.value))
  1043. def format_era(self, char, num):
  1044. width = {3: 'abbreviated', 4: 'wide', 5: 'narrow'}[max(3, num)]
  1045. era = int(self.value.year >= 0)
  1046. return get_era_names(width, self.locale)[era]
  1047. def format_year(self, char, num):
  1048. value = self.value.year
  1049. if char.isupper():
  1050. week = self.get_week_number(self.get_day_of_year())
  1051. if week == 0:
  1052. value -= 1
  1053. year = self.format(value, num)
  1054. if num == 2:
  1055. year = year[-2:]
  1056. return year
  1057. def format_quarter(self, char, num):
  1058. quarter = (self.value.month - 1) // 3 + 1
  1059. if num <= 2:
  1060. return ('%%0%dd' % num) % quarter
  1061. width = {3: 'abbreviated', 4: 'wide', 5: 'narrow'}[num]
  1062. context = {'Q': 'format', 'q': 'stand-alone'}[char]
  1063. return get_quarter_names(width, context, self.locale)[quarter]
  1064. def format_month(self, char, num):
  1065. if num <= 2:
  1066. return ('%%0%dd' % num) % self.value.month
  1067. width = {3: 'abbreviated', 4: 'wide', 5: 'narrow'}[num]
  1068. context = {'M': 'format', 'L': 'stand-alone'}[char]
  1069. return get_month_names(width, context, self.locale)[self.value.month]
  1070. def format_week(self, char, num):
  1071. if char.islower(): # week of year
  1072. day_of_year = self.get_day_of_year()
  1073. week = self.get_week_number(day_of_year)
  1074. if week == 0:
  1075. date = self.value - timedelta(days=day_of_year)
  1076. week = self.get_week_number(self.get_day_of_year(date),
  1077. date.weekday())
  1078. return self.format(week, num)
  1079. else: # week of month
  1080. week = self.get_week_number(self.value.day)
  1081. if week == 0:
  1082. date = self.value - timedelta(days=self.value.day)
  1083. week = self.get_week_number(date.day, date.weekday())
  1084. return '%d' % week
  1085. def format_weekday(self, char='E', num=4):
  1086. """
  1087. Return weekday from parsed datetime according to format pattern.
  1088. >>> format = DateTimeFormat(date(2016, 2, 28), Locale.parse('en_US'))
  1089. >>> format.format_weekday()
  1090. u'Sunday'
  1091. 'E': Day of week - Use one through three letters for the abbreviated day name, four for the full (wide) name,
  1092. five for the narrow name, or six for the short name.
  1093. >>> format.format_weekday('E',2)
  1094. u'Sun'
  1095. 'e': Local day of week. Same as E except adds a numeric value that will depend on the local starting day of the
  1096. week, using one or two letters. For this example, Monday is the first day of the week.
  1097. >>> format.format_weekday('e',2)
  1098. '01'
  1099. 'c': Stand-Alone local day of week - Use one letter for the local numeric value (same as 'e'), three for the
  1100. abbreviated day name, four for the full (wide) name, five for the narrow name, or six for the short name.
  1101. >>> format.format_weekday('c',1)
  1102. '1'
  1103. :param char: pattern format character ('e','E','c')
  1104. :param num: count of format character
  1105. """
  1106. if num < 3:
  1107. if char.islower():
  1108. value = 7 - self.locale.first_week_day + self.value.weekday()
  1109. return self.format(value % 7 + 1, num)
  1110. num = 3
  1111. weekday = self.value.weekday()
  1112. width = {3: 'abbreviated', 4: 'wide', 5: 'narrow', 6: 'short'}[num]
  1113. if char == 'c':
  1114. context = 'stand-alone'
  1115. else:
  1116. context = 'format'
  1117. return get_day_names(width, context, self.locale)[weekday]
  1118. def format_day_of_year(self, num):
  1119. return self.format(self.get_day_of_year(), num)
  1120. def format_day_of_week_in_month(self):
  1121. return '%d' % ((self.value.day - 1) // 7 + 1)
  1122. def format_period(self, char):
  1123. period = {0: 'am', 1: 'pm'}[int(self.value.hour >= 12)]
  1124. for width in ('wide', 'narrow', 'abbreviated'):
  1125. period_names = get_period_names(context='format', width=width, locale=self.locale)
  1126. if period in period_names:
  1127. return period_names[period]
  1128. raise ValueError('Could not format period %s in %s' % (period, self.locale))
  1129. def format_frac_seconds(self, num):
  1130. """ Return fractional seconds.
  1131. Rounds the time's microseconds to the precision given by the number \
  1132. of digits passed in.
  1133. """
  1134. value = self.value.microsecond / 1000000
  1135. return self.format(round(value, num) * 10**num, num)
  1136. def format_milliseconds_in_day(self, num):
  1137. msecs = self.value.microsecond // 1000 + self.value.second * 1000 + \
  1138. self.value.minute * 60000 + self.value.hour * 3600000
  1139. return self.format(msecs, num)
  1140. def format_timezone(self, char, num):
  1141. width = {3: 'short', 4: 'long', 5: 'iso8601'}[max(3, num)]
  1142. if char == 'z':
  1143. return get_timezone_name(self.value, width, locale=self.locale)
  1144. elif char == 'Z':
  1145. if num == 5:
  1146. return get_timezone_gmt(self.value, width, locale=self.locale, return_z=True)
  1147. return get_timezone_gmt(self.value, width, locale=self.locale)
  1148. elif char == 'O':
  1149. if num == 4:
  1150. return get_timezone_gmt(self.value, width, locale=self.locale)
  1151. # TODO: To add support for O:1
  1152. elif char == 'v':
  1153. return get_timezone_name(self.value.tzinfo, width,
  1154. locale=self.locale)
  1155. elif char == 'V':
  1156. if num == 1:
  1157. return get_timezone_name(self.value.tzinfo, width,
  1158. uncommon=True, locale=self.locale)
  1159. elif num == 2:
  1160. return get_timezone_name(self.value.tzinfo, locale=self.locale, return_zone=True)
  1161. elif num == 3:
  1162. return get_timezone_location(self.value.tzinfo, locale=self.locale, return_city=True)
  1163. return get_timezone_location(self.value.tzinfo, locale=self.locale)
  1164. # Included additional elif condition to add support for 'Xx' in timezone format
  1165. elif char == 'X':
  1166. if num == 1:
  1167. return get_timezone_gmt(self.value, width='iso8601_short', locale=self.locale,
  1168. return_z=True)
  1169. elif num in (2, 4):
  1170. return get_timezone_gmt(self.value, width='short', locale=self.locale,
  1171. return_z=True)
  1172. elif num in (3, 5):
  1173. return get_timezone_gmt(self.value, width='iso8601', locale=self.locale,
  1174. return_z=True)
  1175. elif char == 'x':
  1176. if num == 1:
  1177. return get_timezone_gmt(self.value, width='iso8601_short', locale=self.locale)
  1178. elif num in (2, 4):
  1179. return get_timezone_gmt(self.value, width='short', locale=self.locale)
  1180. elif num in (3, 5):
  1181. return get_timezone_gmt(self.value, width='iso8601', locale=self.locale)
  1182. def format(self, value, length):
  1183. return ('%%0%dd' % length) % value
  1184. def get_day_of_year(self, date=None):
  1185. if date is None:
  1186. date = self.value
  1187. return (date - date.replace(month=1, day=1)).days + 1
  1188. def get_week_number(self, day_of_period, day_of_week=None):
  1189. """Return the number of the week of a day within a period. This may be
  1190. the week number in a year or the week number in a month.
  1191. Usually this will return a value equal to or greater than 1, but if the
  1192. first week of the period is so short that it actually counts as the last
  1193. week of the previous period, this function will return 0.
  1194. >>> format = DateTimeFormat(date(2006, 1, 8), Locale.parse('de_DE'))
  1195. >>> format.get_week_number(6)
  1196. 1
  1197. >>> format = DateTimeFormat(date(2006, 1, 8), Locale.parse('en_US'))
  1198. >>> format.get_week_number(6)
  1199. 2
  1200. :param day_of_period: the number of the day in the period (usually
  1201. either the day of month or the day of year)
  1202. :param day_of_week: the week day; if ommitted, the week day of the
  1203. current date is assumed
  1204. """
  1205. if day_of_week is None:
  1206. day_of_week = self.value.weekday()
  1207. first_day = (day_of_week - self.locale.first_week_day -
  1208. day_of_period + 1) % 7
  1209. if first_day < 0:
  1210. first_day += 7
  1211. week_number = (day_of_period + first_day - 1) // 7
  1212. if 7 - first_day >= self.locale.min_week_days:
  1213. week_number += 1
  1214. return week_number
  1215. PATTERN_CHARS = {
  1216. 'G': [1, 2, 3, 4, 5], # era
  1217. 'y': None, 'Y': None, 'u': None, # year
  1218. 'Q': [1, 2, 3, 4, 5], 'q': [1, 2, 3, 4, 5], # quarter
  1219. 'M': [1, 2, 3, 4, 5], 'L': [1, 2, 3, 4, 5], # month
  1220. 'w': [1, 2], 'W': [1], # week
  1221. 'd': [1, 2], 'D': [1, 2, 3], 'F': [1], 'g': None, # day
  1222. 'E': [1, 2, 3, 4, 5, 6], 'e': [1, 2, 3, 4, 5, 6], 'c': [1, 3, 4, 5, 6], # week day
  1223. 'a': [1], # period
  1224. 'h': [1, 2], 'H': [1, 2], 'K': [1, 2], 'k': [1, 2], # hour
  1225. 'm': [1, 2], # minute
  1226. 's': [1, 2], 'S': None, 'A': None, # second
  1227. 'z': [1, 2, 3, 4], 'Z': [1, 2, 3, 4, 5], 'O': [1, 4], 'v': [1, 4], # zone
  1228. 'V': [1, 2, 3, 4], 'x': [1, 2, 3, 4, 5], 'X': [1, 2, 3, 4, 5] # zone
  1229. }
  1230. #: The pattern characters declared in the Date Field Symbol Table
  1231. #: (http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table)
  1232. #: in order of decreasing magnitude.
  1233. PATTERN_CHAR_ORDER = "GyYuUQqMLlwWdDFgEecabBChHKkjJmsSAzZOvVXx"
  1234. _pattern_cache = {}
  1235. def parse_pattern(pattern):
  1236. """Parse date, time, and datetime format patterns.
  1237. >>> parse_pattern("MMMMd").format
  1238. u'%(MMMM)s%(d)s'
  1239. >>> parse_pattern("MMM d, yyyy").format
  1240. u'%(MMM)s %(d)s, %(yyyy)s'
  1241. Pattern can contain literal strings in single quotes:
  1242. >>> parse_pattern("H:mm' Uhr 'z").format
  1243. u'%(H)s:%(mm)s Uhr %(z)s'
  1244. An actual single quote can be used by using two adjacent single quote
  1245. characters:
  1246. >>> parse_pattern("hh' o''clock'").format
  1247. u"%(hh)s o'clock"
  1248. :param pattern: the formatting pattern to parse
  1249. """
  1250. if type(pattern) is DateTimePattern:
  1251. return pattern
  1252. if pattern in _pattern_cache:
  1253. return _pattern_cache[pattern]
  1254. result = []
  1255. for tok_type, tok_value in tokenize_pattern(pattern):
  1256. if tok_type == "chars":
  1257. result.append(tok_value.replace('%', '%%'))
  1258. elif tok_type == "field":
  1259. fieldchar, fieldnum = tok_value
  1260. limit = PATTERN_CHARS[fieldchar]
  1261. if limit and fieldnum not in limit:
  1262. raise ValueError('Invalid length for field: %r'
  1263. % (fieldchar * fieldnum))
  1264. result.append('%%(%s)s' % (fieldchar * fieldnum))
  1265. else:
  1266. raise NotImplementedError("Unknown token type: %s" % tok_type)
  1267. _pattern_cache[pattern] = pat = DateTimePattern(pattern, u''.join(result))
  1268. return pat
  1269. def tokenize_pattern(pattern):
  1270. """
  1271. Tokenize date format patterns.
  1272. Returns a list of (token_type, token_value) tuples.
  1273. ``token_type`` may be either "chars" or "field".
  1274. For "chars" tokens, the value is the literal value.
  1275. For "field" tokens, the value is a tuple of (field character, repetition count).
  1276. :param pattern: Pattern string
  1277. :type pattern: str
  1278. :rtype: list[tuple]
  1279. """
  1280. result = []
  1281. quotebuf = None
  1282. charbuf = []
  1283. fieldchar = ['']
  1284. fieldnum = [0]
  1285. def append_chars():
  1286. result.append(('chars', ''.join(charbuf).replace('\0', "'")))
  1287. del charbuf[:]
  1288. def append_field():
  1289. result.append(('field', (fieldchar[0], fieldnum[0])))
  1290. fieldchar[0] = ''
  1291. fieldnum[0] = 0
  1292. for idx, char in enumerate(pattern.replace("''", '\0')):
  1293. if quotebuf is None:
  1294. if char == "'": # quote started
  1295. if fieldchar[0]:
  1296. append_field()
  1297. elif charbuf:
  1298. append_chars()
  1299. quotebuf = []
  1300. elif char in PATTERN_CHARS:
  1301. if charbuf:
  1302. append_chars()
  1303. if char == fieldchar[0]:
  1304. fieldnum[0] += 1
  1305. else:
  1306. if fieldchar[0]:
  1307. append_field()
  1308. fieldchar[0] = char
  1309. fieldnum[0] = 1
  1310. else:
  1311. if fieldchar[0]:
  1312. append_field()
  1313. charbuf.append(char)
  1314. elif quotebuf is not None:
  1315. if char == "'": # end of quote
  1316. charbuf.extend(quotebuf)
  1317. quotebuf = None
  1318. else: # inside quote
  1319. quotebuf.append(char)
  1320. if fieldchar[0]:
  1321. append_field()
  1322. elif charbuf:
  1323. append_chars()
  1324. return result
  1325. def untokenize_pattern(tokens):
  1326. """
  1327. Turn a date format pattern token stream back into a string.
  1328. This is the reverse operation of ``tokenize_pattern``.
  1329. :type tokens: Iterable[tuple]
  1330. :rtype: str
  1331. """
  1332. output = []
  1333. for tok_type, tok_value in tokens:
  1334. if tok_type == "field":
  1335. output.append(tok_value[0] * tok_value[1])
  1336. elif tok_type == "chars":
  1337. if not any(ch in PATTERN_CHARS for ch in tok_value): # No need to quote
  1338. output.append(tok_value)
  1339. else:
  1340. output.append("'%s'" % tok_value.replace("'", "''"))
  1341. return "".join(output)
  1342. def split_interval_pattern(pattern):
  1343. """
  1344. Split an interval-describing datetime pattern into multiple pieces.
  1345. > The pattern is then designed to be broken up into two pieces by determining the first repeating field.
  1346. - http://www.unicode.org/reports/tr35/tr35-dates.html#intervalFormats
  1347. >>> split_interval_pattern(u'E d.M. \u2013 E d.M.')
  1348. [u'E d.M. \u2013 ', 'E d.M.']
  1349. >>> split_interval_pattern("Y 'text' Y 'more text'")
  1350. ["Y 'text '", "Y 'more text'"]
  1351. >>> split_interval_pattern(u"E, MMM d \u2013 E")
  1352. [u'E, MMM d \u2013 ', u'E']
  1353. >>> split_interval_pattern("MMM d")
  1354. ['MMM d']
  1355. >>> split_interval_pattern("y G")
  1356. ['y G']
  1357. >>> split_interval_pattern(u"MMM d \u2013 d")
  1358. [u'MMM d \u2013 ', u'd']
  1359. :param pattern: Interval pattern string
  1360. :return: list of "subpatterns"
  1361. """
  1362. seen_fields = set()
  1363. parts = [[]]
  1364. for tok_type, tok_value in tokenize_pattern(pattern):
  1365. if tok_type == "field":
  1366. if tok_value[0] in seen_fields: # Repeated field
  1367. parts.append([])
  1368. seen_fields.clear()
  1369. seen_fields.add(tok_value[0])
  1370. parts[-1].append((tok_type, tok_value))
  1371. return [untokenize_pattern(tokens) for tokens in parts]
  1372. def match_skeleton(skeleton, options, allow_different_fields=False):
  1373. """
  1374. Find the closest match for the given datetime skeleton among the options given.
  1375. This uses the rules outlined in the TR35 document.
  1376. >>> match_skeleton('yMMd', ('yMd', 'yMMMd'))
  1377. 'yMd'
  1378. >>> match_skeleton('yMMd', ('jyMMd',), allow_different_fields=True)
  1379. 'jyMMd'
  1380. >>> match_skeleton('yMMd', ('qyMMd',), allow_different_fields=False)
  1381. >>> match_skeleton('hmz', ('hmv',))
  1382. 'hmv'
  1383. :param skeleton: The skeleton to match
  1384. :type skeleton: str
  1385. :param options: An iterable of other skeletons to match against
  1386. :type options: Iterable[str]
  1387. :return: The closest skeleton match, or if no match was found, None.
  1388. :rtype: str|None
  1389. """
  1390. # TODO: maybe implement pattern expansion?
  1391. # Based on the implementation in
  1392. # http://source.icu-project.org/repos/icu/icu4j/trunk/main/classes/core/src/com/ibm/icu/text/DateIntervalInfo.java
  1393. # Filter out falsy values and sort for stability; when `interval_formats` is passed in, there may be a None key.
  1394. options = sorted(option for option in options if option)
  1395. if 'z' in skeleton and not any('z' in option for option in options):
  1396. skeleton = skeleton.replace('z', 'v')
  1397. get_input_field_width = dict(t[1] for t in tokenize_pattern(skeleton) if t[0] == "field").get
  1398. best_skeleton = None
  1399. best_distance = None
  1400. for option in options:
  1401. get_opt_field_width = dict(t[1] for t in tokenize_pattern(option) if t[0] == "field").get
  1402. distance = 0
  1403. for field in PATTERN_CHARS:
  1404. input_width = get_input_field_width(field, 0)
  1405. opt_width = get_opt_field_width(field, 0)
  1406. if input_width == opt_width:
  1407. continue
  1408. if opt_width == 0 or input_width == 0:
  1409. if not allow_different_fields: # This one is not okay
  1410. option = None
  1411. break
  1412. distance += 0x1000 # Magic weight constant for "entirely different fields"
  1413. elif field == 'M' and ((input_width > 2 and opt_width <= 2) or (input_width <= 2 and opt_width > 2)):
  1414. distance += 0x100 # Magic weight for "text turns into a number"
  1415. else:
  1416. distance += abs(input_width - opt_width)
  1417. if not option: # We lost the option along the way (probably due to "allow_different_fields")
  1418. continue
  1419. if not best_skeleton or distance < best_distance:
  1420. best_skeleton = option
  1421. best_distance = distance
  1422. if distance == 0: # Found a perfect match!
  1423. break
  1424. return best_skeleton