dates.py 75 KB

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