dates.py 74 KB

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