dates.py 66 KB

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