dates.py 65 KB

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