Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

_parser.py 56KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578
  1. # -*- coding: utf-8 -*-
  2. """
  3. This module offers a generic date/time string parser which is able to parse
  4. most known formats to represent a date and/or time.
  5. This module attempts to be forgiving with regards to unlikely input formats,
  6. returning a datetime object even for dates which are ambiguous. If an element
  7. of a date/time stamp is omitted, the following rules are applied:
  8. - If AM or PM is left unspecified, a 24-hour clock is assumed, however, an hour
  9. on a 12-hour clock (``0 <= hour <= 12``) *must* be specified if AM or PM is
  10. specified.
  11. - If a time zone is omitted, a timezone-naive datetime is returned.
  12. If any other elements are missing, they are taken from the
  13. :class:`datetime.datetime` object passed to the parameter ``default``. If this
  14. results in a day number exceeding the valid number of days per month, the
  15. value falls back to the end of the month.
  16. Additional resources about date/time string formats can be found below:
  17. - `A summary of the international standard date and time notation
  18. <http://www.cl.cam.ac.uk/~mgk25/iso-time.html>`_
  19. - `W3C Date and Time Formats <http://www.w3.org/TR/NOTE-datetime>`_
  20. - `Time Formats (Planetary Rings Node) <https://pds-rings.seti.org:443/tools/time_formats.html>`_
  21. - `CPAN ParseDate module
  22. <http://search.cpan.org/~muir/Time-modules-2013.0912/lib/Time/ParseDate.pm>`_
  23. - `Java SimpleDateFormat Class
  24. <https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html>`_
  25. """
  26. from __future__ import unicode_literals
  27. import datetime
  28. import re
  29. import string
  30. import time
  31. import warnings
  32. from calendar import monthrange
  33. from io import StringIO
  34. import six
  35. from six import binary_type, integer_types, text_type
  36. from decimal import Decimal
  37. from warnings import warn
  38. from .. import relativedelta
  39. from .. import tz
  40. __all__ = ["parse", "parserinfo"]
  41. # TODO: pandas.core.tools.datetimes imports this explicitly. Might be worth
  42. # making public and/or figuring out if there is something we can
  43. # take off their plate.
  44. class _timelex(object):
  45. # Fractional seconds are sometimes split by a comma
  46. _split_decimal = re.compile("([.,])")
  47. def __init__(self, instream):
  48. if six.PY2:
  49. # In Python 2, we can't duck type properly because unicode has
  50. # a 'decode' function, and we'd be double-decoding
  51. if isinstance(instream, (binary_type, bytearray)):
  52. instream = instream.decode()
  53. else:
  54. if getattr(instream, 'decode', None) is not None:
  55. instream = instream.decode()
  56. if isinstance(instream, text_type):
  57. instream = StringIO(instream)
  58. elif getattr(instream, 'read', None) is None:
  59. raise TypeError('Parser must be a string or character stream, not '
  60. '{itype}'.format(itype=instream.__class__.__name__))
  61. self.instream = instream
  62. self.charstack = []
  63. self.tokenstack = []
  64. self.eof = False
  65. def get_token(self):
  66. """
  67. This function breaks the time string into lexical units (tokens), which
  68. can be parsed by the parser. Lexical units are demarcated by changes in
  69. the character set, so any continuous string of letters is considered
  70. one unit, any continuous string of numbers is considered one unit.
  71. The main complication arises from the fact that dots ('.') can be used
  72. both as separators (e.g. "Sep.20.2009") or decimal points (e.g.
  73. "4:30:21.447"). As such, it is necessary to read the full context of
  74. any dot-separated strings before breaking it into tokens; as such, this
  75. function maintains a "token stack", for when the ambiguous context
  76. demands that multiple tokens be parsed at once.
  77. """
  78. if self.tokenstack:
  79. return self.tokenstack.pop(0)
  80. seenletters = False
  81. token = None
  82. state = None
  83. while not self.eof:
  84. # We only realize that we've reached the end of a token when we
  85. # find a character that's not part of the current token - since
  86. # that character may be part of the next token, it's stored in the
  87. # charstack.
  88. if self.charstack:
  89. nextchar = self.charstack.pop(0)
  90. else:
  91. nextchar = self.instream.read(1)
  92. while nextchar == '\x00':
  93. nextchar = self.instream.read(1)
  94. if not nextchar:
  95. self.eof = True
  96. break
  97. elif not state:
  98. # First character of the token - determines if we're starting
  99. # to parse a word, a number or something else.
  100. token = nextchar
  101. if self.isword(nextchar):
  102. state = 'a'
  103. elif self.isnum(nextchar):
  104. state = '0'
  105. elif self.isspace(nextchar):
  106. token = ' '
  107. break # emit token
  108. else:
  109. break # emit token
  110. elif state == 'a':
  111. # If we've already started reading a word, we keep reading
  112. # letters until we find something that's not part of a word.
  113. seenletters = True
  114. if self.isword(nextchar):
  115. token += nextchar
  116. elif nextchar == '.':
  117. token += nextchar
  118. state = 'a.'
  119. else:
  120. self.charstack.append(nextchar)
  121. break # emit token
  122. elif state == '0':
  123. # If we've already started reading a number, we keep reading
  124. # numbers until we find something that doesn't fit.
  125. if self.isnum(nextchar):
  126. token += nextchar
  127. elif nextchar == '.' or (nextchar == ',' and len(token) >= 2):
  128. token += nextchar
  129. state = '0.'
  130. else:
  131. self.charstack.append(nextchar)
  132. break # emit token
  133. elif state == 'a.':
  134. # If we've seen some letters and a dot separator, continue
  135. # parsing, and the tokens will be broken up later.
  136. seenletters = True
  137. if nextchar == '.' or self.isword(nextchar):
  138. token += nextchar
  139. elif self.isnum(nextchar) and token[-1] == '.':
  140. token += nextchar
  141. state = '0.'
  142. else:
  143. self.charstack.append(nextchar)
  144. break # emit token
  145. elif state == '0.':
  146. # If we've seen at least one dot separator, keep going, we'll
  147. # break up the tokens later.
  148. if nextchar == '.' or self.isnum(nextchar):
  149. token += nextchar
  150. elif self.isword(nextchar) and token[-1] == '.':
  151. token += nextchar
  152. state = 'a.'
  153. else:
  154. self.charstack.append(nextchar)
  155. break # emit token
  156. if (state in ('a.', '0.') and (seenletters or token.count('.') > 1 or
  157. token[-1] in '.,')):
  158. l = self._split_decimal.split(token)
  159. token = l[0]
  160. for tok in l[1:]:
  161. if tok:
  162. self.tokenstack.append(tok)
  163. if state == '0.' and token.count('.') == 0:
  164. token = token.replace(',', '.')
  165. return token
  166. def __iter__(self):
  167. return self
  168. def __next__(self):
  169. token = self.get_token()
  170. if token is None:
  171. raise StopIteration
  172. return token
  173. def next(self):
  174. return self.__next__() # Python 2.x support
  175. @classmethod
  176. def split(cls, s):
  177. return list(cls(s))
  178. @classmethod
  179. def isword(cls, nextchar):
  180. """ Whether or not the next character is part of a word """
  181. return nextchar.isalpha()
  182. @classmethod
  183. def isnum(cls, nextchar):
  184. """ Whether the next character is part of a number """
  185. return nextchar.isdigit()
  186. @classmethod
  187. def isspace(cls, nextchar):
  188. """ Whether the next character is whitespace """
  189. return nextchar.isspace()
  190. class _resultbase(object):
  191. def __init__(self):
  192. for attr in self.__slots__:
  193. setattr(self, attr, None)
  194. def _repr(self, classname):
  195. l = []
  196. for attr in self.__slots__:
  197. value = getattr(self, attr)
  198. if value is not None:
  199. l.append("%s=%s" % (attr, repr(value)))
  200. return "%s(%s)" % (classname, ", ".join(l))
  201. def __len__(self):
  202. return (sum(getattr(self, attr) is not None
  203. for attr in self.__slots__))
  204. def __repr__(self):
  205. return self._repr(self.__class__.__name__)
  206. class parserinfo(object):
  207. """
  208. Class which handles what inputs are accepted. Subclass this to customize
  209. the language and acceptable values for each parameter.
  210. :param dayfirst:
  211. Whether to interpret the first value in an ambiguous 3-integer date
  212. (e.g. 01/05/09) as the day (``True``) or month (``False``). If
  213. ``yearfirst`` is set to ``True``, this distinguishes between YDM
  214. and YMD. Default is ``False``.
  215. :param yearfirst:
  216. Whether to interpret the first value in an ambiguous 3-integer date
  217. (e.g. 01/05/09) as the year. If ``True``, the first number is taken
  218. to be the year, otherwise the last number is taken to be the year.
  219. Default is ``False``.
  220. """
  221. # m from a.m/p.m, t from ISO T separator
  222. JUMP = [" ", ".", ",", ";", "-", "/", "'",
  223. "at", "on", "and", "ad", "m", "t", "of",
  224. "st", "nd", "rd", "th"]
  225. WEEKDAYS = [("Mon", "Monday"),
  226. ("Tue", "Tuesday"), # TODO: "Tues"
  227. ("Wed", "Wednesday"),
  228. ("Thu", "Thursday"), # TODO: "Thurs"
  229. ("Fri", "Friday"),
  230. ("Sat", "Saturday"),
  231. ("Sun", "Sunday")]
  232. MONTHS = [("Jan", "January"),
  233. ("Feb", "February"), # TODO: "Febr"
  234. ("Mar", "March"),
  235. ("Apr", "April"),
  236. ("May", "May"),
  237. ("Jun", "June"),
  238. ("Jul", "July"),
  239. ("Aug", "August"),
  240. ("Sep", "Sept", "September"),
  241. ("Oct", "October"),
  242. ("Nov", "November"),
  243. ("Dec", "December")]
  244. HMS = [("h", "hour", "hours"),
  245. ("m", "minute", "minutes"),
  246. ("s", "second", "seconds")]
  247. AMPM = [("am", "a"),
  248. ("pm", "p")]
  249. UTCZONE = ["UTC", "GMT", "Z"]
  250. PERTAIN = ["of"]
  251. TZOFFSET = {}
  252. # TODO: ERA = ["AD", "BC", "CE", "BCE", "Stardate",
  253. # "Anno Domini", "Year of Our Lord"]
  254. def __init__(self, dayfirst=False, yearfirst=False):
  255. self._jump = self._convert(self.JUMP)
  256. self._weekdays = self._convert(self.WEEKDAYS)
  257. self._months = self._convert(self.MONTHS)
  258. self._hms = self._convert(self.HMS)
  259. self._ampm = self._convert(self.AMPM)
  260. self._utczone = self._convert(self.UTCZONE)
  261. self._pertain = self._convert(self.PERTAIN)
  262. self.dayfirst = dayfirst
  263. self.yearfirst = yearfirst
  264. self._year = time.localtime().tm_year
  265. self._century = self._year // 100 * 100
  266. def _convert(self, lst):
  267. dct = {}
  268. for i, v in enumerate(lst):
  269. if isinstance(v, tuple):
  270. for v in v:
  271. dct[v.lower()] = i
  272. else:
  273. dct[v.lower()] = i
  274. return dct
  275. def jump(self, name):
  276. return name.lower() in self._jump
  277. def weekday(self, name):
  278. try:
  279. return self._weekdays[name.lower()]
  280. except KeyError:
  281. pass
  282. return None
  283. def month(self, name):
  284. try:
  285. return self._months[name.lower()] + 1
  286. except KeyError:
  287. pass
  288. return None
  289. def hms(self, name):
  290. try:
  291. return self._hms[name.lower()]
  292. except KeyError:
  293. return None
  294. def ampm(self, name):
  295. try:
  296. return self._ampm[name.lower()]
  297. except KeyError:
  298. return None
  299. def pertain(self, name):
  300. return name.lower() in self._pertain
  301. def utczone(self, name):
  302. return name.lower() in self._utczone
  303. def tzoffset(self, name):
  304. if name in self._utczone:
  305. return 0
  306. return self.TZOFFSET.get(name)
  307. def convertyear(self, year, century_specified=False):
  308. """
  309. Converts two-digit years to year within [-50, 49]
  310. range of self._year (current local time)
  311. """
  312. # Function contract is that the year is always positive
  313. assert year >= 0
  314. if year < 100 and not century_specified:
  315. # assume current century to start
  316. year += self._century
  317. if year >= self._year + 50: # if too far in future
  318. year -= 100
  319. elif year < self._year - 50: # if too far in past
  320. year += 100
  321. return year
  322. def validate(self, res):
  323. # move to info
  324. if res.year is not None:
  325. res.year = self.convertyear(res.year, res.century_specified)
  326. if res.tzoffset == 0 and not res.tzname or res.tzname == 'Z':
  327. res.tzname = "UTC"
  328. res.tzoffset = 0
  329. elif res.tzoffset != 0 and res.tzname and self.utczone(res.tzname):
  330. res.tzoffset = 0
  331. return True
  332. class _ymd(list):
  333. def __init__(self, *args, **kwargs):
  334. super(self.__class__, self).__init__(*args, **kwargs)
  335. self.century_specified = False
  336. self.dstridx = None
  337. self.mstridx = None
  338. self.ystridx = None
  339. @property
  340. def has_year(self):
  341. return self.ystridx is not None
  342. @property
  343. def has_month(self):
  344. return self.mstridx is not None
  345. @property
  346. def has_day(self):
  347. return self.dstridx is not None
  348. def could_be_day(self, value):
  349. if self.has_day:
  350. return False
  351. elif not self.has_month:
  352. return 1 <= value <= 31
  353. elif not self.has_year:
  354. # Be permissive, assume leapyear
  355. month = self[self.mstridx]
  356. return 1 <= value <= monthrange(2000, month)[1]
  357. else:
  358. month = self[self.mstridx]
  359. year = self[self.ystridx]
  360. return 1 <= value <= monthrange(year, month)[1]
  361. def append(self, val, label=None):
  362. if hasattr(val, '__len__'):
  363. if val.isdigit() and len(val) > 2:
  364. self.century_specified = True
  365. if label not in [None, 'Y']: # pragma: no cover
  366. raise ValueError(label)
  367. label = 'Y'
  368. elif val > 100:
  369. self.century_specified = True
  370. if label not in [None, 'Y']: # pragma: no cover
  371. raise ValueError(label)
  372. label = 'Y'
  373. super(self.__class__, self).append(int(val))
  374. if label == 'M':
  375. if self.has_month:
  376. raise ValueError('Month is already set')
  377. self.mstridx = len(self) - 1
  378. elif label == 'D':
  379. if self.has_day:
  380. raise ValueError('Day is already set')
  381. self.dstridx = len(self) - 1
  382. elif label == 'Y':
  383. if self.has_year:
  384. raise ValueError('Year is already set')
  385. self.ystridx = len(self) - 1
  386. def _resolve_from_stridxs(self, strids):
  387. """
  388. Try to resolve the identities of year/month/day elements using
  389. ystridx, mstridx, and dstridx, if enough of these are specified.
  390. """
  391. if len(self) == 3 and len(strids) == 2:
  392. # we can back out the remaining stridx value
  393. missing = [x for x in range(3) if x not in strids.values()]
  394. key = [x for x in ['y', 'm', 'd'] if x not in strids]
  395. assert len(missing) == len(key) == 1
  396. key = key[0]
  397. val = missing[0]
  398. strids[key] = val
  399. assert len(self) == len(strids) # otherwise this should not be called
  400. out = {key: self[strids[key]] for key in strids}
  401. return (out.get('y'), out.get('m'), out.get('d'))
  402. def resolve_ymd(self, yearfirst, dayfirst):
  403. len_ymd = len(self)
  404. year, month, day = (None, None, None)
  405. strids = (('y', self.ystridx),
  406. ('m', self.mstridx),
  407. ('d', self.dstridx))
  408. strids = {key: val for key, val in strids if val is not None}
  409. if (len(self) == len(strids) > 0 or
  410. (len(self) == 3 and len(strids) == 2)):
  411. return self._resolve_from_stridxs(strids)
  412. mstridx = self.mstridx
  413. if len_ymd > 3:
  414. raise ValueError("More than three YMD values")
  415. elif len_ymd == 1 or (mstridx is not None and len_ymd == 2):
  416. # One member, or two members with a month string
  417. if mstridx is not None:
  418. month = self[mstridx]
  419. # since mstridx is 0 or 1, self[mstridx-1] always
  420. # looks up the other element
  421. other = self[mstridx - 1]
  422. else:
  423. other = self[0]
  424. if len_ymd > 1 or mstridx is None:
  425. if other > 31:
  426. year = other
  427. else:
  428. day = other
  429. elif len_ymd == 2:
  430. # Two members with numbers
  431. if self[0] > 31:
  432. # 99-01
  433. year, month = self
  434. elif self[1] > 31:
  435. # 01-99
  436. month, year = self
  437. elif dayfirst and self[1] <= 12:
  438. # 13-01
  439. day, month = self
  440. else:
  441. # 01-13
  442. month, day = self
  443. elif len_ymd == 3:
  444. # Three members
  445. if mstridx == 0:
  446. if self[1] > 31:
  447. # Apr-2003-25
  448. month, year, day = self
  449. else:
  450. month, day, year = self
  451. elif mstridx == 1:
  452. if self[0] > 31 or (yearfirst and self[2] <= 31):
  453. # 99-Jan-01
  454. year, month, day = self
  455. else:
  456. # 01-Jan-01
  457. # Give precendence to day-first, since
  458. # two-digit years is usually hand-written.
  459. day, month, year = self
  460. elif mstridx == 2:
  461. # WTF!?
  462. if self[1] > 31:
  463. # 01-99-Jan
  464. day, year, month = self
  465. else:
  466. # 99-01-Jan
  467. year, day, month = self
  468. else:
  469. if (self[0] > 31 or
  470. self.ystridx == 0 or
  471. (yearfirst and self[1] <= 12 and self[2] <= 31)):
  472. # 99-01-01
  473. if dayfirst and self[2] <= 12:
  474. year, day, month = self
  475. else:
  476. year, month, day = self
  477. elif self[0] > 12 or (dayfirst and self[1] <= 12):
  478. # 13-01-01
  479. day, month, year = self
  480. else:
  481. # 01-13-01
  482. month, day, year = self
  483. return year, month, day
  484. class parser(object):
  485. def __init__(self, info=None):
  486. self.info = info or parserinfo()
  487. def parse(self, timestr, default=None,
  488. ignoretz=False, tzinfos=None, **kwargs):
  489. """
  490. Parse the date/time string into a :class:`datetime.datetime` object.
  491. :param timestr:
  492. Any date/time string using the supported formats.
  493. :param default:
  494. The default datetime object, if this is a datetime object and not
  495. ``None``, elements specified in ``timestr`` replace elements in the
  496. default object.
  497. :param ignoretz:
  498. If set ``True``, time zones in parsed strings are ignored and a
  499. naive :class:`datetime.datetime` object is returned.
  500. :param tzinfos:
  501. Additional time zone names / aliases which may be present in the
  502. string. This argument maps time zone names (and optionally offsets
  503. from those time zones) to time zones. This parameter can be a
  504. dictionary with timezone aliases mapping time zone names to time
  505. zones or a function taking two parameters (``tzname`` and
  506. ``tzoffset``) and returning a time zone.
  507. The timezones to which the names are mapped can be an integer
  508. offset from UTC in seconds or a :class:`tzinfo` object.
  509. .. doctest::
  510. :options: +NORMALIZE_WHITESPACE
  511. >>> from dateutil.parser import parse
  512. >>> from dateutil.tz import gettz
  513. >>> tzinfos = {"BRST": -7200, "CST": gettz("America/Chicago")}
  514. >>> parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos)
  515. datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -7200))
  516. >>> parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos)
  517. datetime.datetime(2012, 1, 19, 17, 21,
  518. tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago'))
  519. This parameter is ignored if ``ignoretz`` is set.
  520. :param \\*\\*kwargs:
  521. Keyword arguments as passed to ``_parse()``.
  522. :return:
  523. Returns a :class:`datetime.datetime` object or, if the
  524. ``fuzzy_with_tokens`` option is ``True``, returns a tuple, the
  525. first element being a :class:`datetime.datetime` object, the second
  526. a tuple containing the fuzzy tokens.
  527. :raises ValueError:
  528. Raised for invalid or unknown string format, if the provided
  529. :class:`tzinfo` is not in a valid format, or if an invalid date
  530. would be created.
  531. :raises TypeError:
  532. Raised for non-string or character stream input.
  533. :raises OverflowError:
  534. Raised if the parsed date exceeds the largest valid C integer on
  535. your system.
  536. """
  537. if default is None:
  538. default = datetime.datetime.now().replace(hour=0, minute=0,
  539. second=0, microsecond=0)
  540. res, skipped_tokens = self._parse(timestr, **kwargs)
  541. if res is None:
  542. raise ValueError("Unknown string format:", timestr)
  543. if len(res) == 0:
  544. raise ValueError("String does not contain a date:", timestr)
  545. ret = self._build_naive(res, default)
  546. if not ignoretz:
  547. ret = self._build_tzaware(ret, res, tzinfos)
  548. if kwargs.get('fuzzy_with_tokens', False):
  549. return ret, skipped_tokens
  550. else:
  551. return ret
  552. class _result(_resultbase):
  553. __slots__ = ["year", "month", "day", "weekday",
  554. "hour", "minute", "second", "microsecond",
  555. "tzname", "tzoffset", "ampm","any_unused_tokens"]
  556. def _parse(self, timestr, dayfirst=None, yearfirst=None, fuzzy=False,
  557. fuzzy_with_tokens=False):
  558. """
  559. Private method which performs the heavy lifting of parsing, called from
  560. ``parse()``, which passes on its ``kwargs`` to this function.
  561. :param timestr:
  562. The string to parse.
  563. :param dayfirst:
  564. Whether to interpret the first value in an ambiguous 3-integer date
  565. (e.g. 01/05/09) as the day (``True``) or month (``False``). If
  566. ``yearfirst`` is set to ``True``, this distinguishes between YDM
  567. and YMD. If set to ``None``, this value is retrieved from the
  568. current :class:`parserinfo` object (which itself defaults to
  569. ``False``).
  570. :param yearfirst:
  571. Whether to interpret the first value in an ambiguous 3-integer date
  572. (e.g. 01/05/09) as the year. If ``True``, the first number is taken
  573. to be the year, otherwise the last number is taken to be the year.
  574. If this is set to ``None``, the value is retrieved from the current
  575. :class:`parserinfo` object (which itself defaults to ``False``).
  576. :param fuzzy:
  577. Whether to allow fuzzy parsing, allowing for string like "Today is
  578. January 1, 2047 at 8:21:00AM".
  579. :param fuzzy_with_tokens:
  580. If ``True``, ``fuzzy`` is automatically set to True, and the parser
  581. will return a tuple where the first element is the parsed
  582. :class:`datetime.datetime` datetimestamp and the second element is
  583. a tuple containing the portions of the string which were ignored:
  584. .. doctest::
  585. >>> from dateutil.parser import parse
  586. >>> parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True)
  587. (datetime.datetime(2047, 1, 1, 8, 21), (u'Today is ', u' ', u'at '))
  588. """
  589. if fuzzy_with_tokens:
  590. fuzzy = True
  591. info = self.info
  592. if dayfirst is None:
  593. dayfirst = info.dayfirst
  594. if yearfirst is None:
  595. yearfirst = info.yearfirst
  596. res = self._result()
  597. l = _timelex.split(timestr) # Splits the timestr into tokens
  598. skipped_idxs = []
  599. # year/month/day list
  600. ymd = _ymd()
  601. len_l = len(l)
  602. i = 0
  603. try:
  604. while i < len_l:
  605. # Check if it's a number
  606. value_repr = l[i]
  607. try:
  608. value = float(value_repr)
  609. except ValueError:
  610. value = None
  611. if value is not None:
  612. # Numeric token
  613. i = self._parse_numeric_token(l, i, info, ymd, res, fuzzy)
  614. # Check weekday
  615. elif info.weekday(l[i]) is not None:
  616. value = info.weekday(l[i])
  617. res.weekday = value
  618. # Check month name
  619. elif info.month(l[i]) is not None:
  620. value = info.month(l[i])
  621. ymd.append(value, 'M')
  622. if i + 1 < len_l:
  623. if l[i + 1] in ('-', '/'):
  624. # Jan-01[-99]
  625. sep = l[i + 1]
  626. ymd.append(l[i + 2])
  627. if i + 3 < len_l and l[i + 3] == sep:
  628. # Jan-01-99
  629. ymd.append(l[i + 4])
  630. i += 2
  631. i += 2
  632. elif (i + 4 < len_l and l[i + 1] == l[i + 3] == ' ' and
  633. info.pertain(l[i + 2])):
  634. # Jan of 01
  635. # In this case, 01 is clearly year
  636. if l[i + 4].isdigit():
  637. # Convert it here to become unambiguous
  638. value = int(l[i + 4])
  639. year = str(info.convertyear(value))
  640. ymd.append(year, 'Y')
  641. else:
  642. # Wrong guess
  643. pass
  644. # TODO: not hit in tests
  645. i += 4
  646. # Check am/pm
  647. elif info.ampm(l[i]) is not None:
  648. value = info.ampm(l[i])
  649. val_is_ampm = self._ampm_valid(res.hour, res.ampm, fuzzy)
  650. if val_is_ampm:
  651. res.hour = self._adjust_ampm(res.hour, value)
  652. res.ampm = value
  653. elif fuzzy:
  654. skipped_idxs.append(i)
  655. # Check for a timezone name
  656. elif self._could_be_tzname(res.hour, res.tzname, res.tzoffset, l[i]):
  657. res.tzname = l[i]
  658. res.tzoffset = info.tzoffset(res.tzname)
  659. # Check for something like GMT+3, or BRST+3. Notice
  660. # that it doesn't mean "I am 3 hours after GMT", but
  661. # "my time +3 is GMT". If found, we reverse the
  662. # logic so that timezone parsing code will get it
  663. # right.
  664. if i + 1 < len_l and l[i + 1] in ('+', '-'):
  665. l[i + 1] = ('+', '-')[l[i + 1] == '+']
  666. res.tzoffset = None
  667. if info.utczone(res.tzname):
  668. # With something like GMT+3, the timezone
  669. # is *not* GMT.
  670. res.tzname = None
  671. # Check for a numbered timezone
  672. elif res.hour is not None and l[i] in ('+', '-'):
  673. signal = (-1, 1)[l[i] == '+']
  674. len_li = len(l[i + 1])
  675. # TODO: check that l[i + 1] is integer?
  676. if len_li == 4:
  677. # -0300
  678. hour_offset = int(l[i + 1][:2])
  679. min_offset = int(l[i + 1][2:])
  680. elif i + 2 < len_l and l[i + 2] == ':':
  681. # -03:00
  682. hour_offset = int(l[i + 1])
  683. min_offset = int(l[i + 3]) # TODO: Check that l[i+3] is minute-like?
  684. i += 2
  685. elif len_li <= 2:
  686. # -[0]3
  687. hour_offset = int(l[i + 1][:2])
  688. min_offset = 0
  689. else:
  690. raise ValueError(timestr)
  691. res.tzoffset = signal * (hour_offset * 3600 + min_offset * 60)
  692. # Look for a timezone name between parenthesis
  693. if (i + 5 < len_l and
  694. info.jump(l[i + 2]) and l[i + 3] == '(' and
  695. l[i + 5] == ')' and
  696. 3 <= len(l[i + 4]) and
  697. self._could_be_tzname(res.hour, res.tzname,
  698. None, l[i + 4])):
  699. # -0300 (BRST)
  700. res.tzname = l[i + 4]
  701. i += 4
  702. i += 1
  703. # Check jumps
  704. elif not (info.jump(l[i]) or fuzzy):
  705. raise ValueError(timestr)
  706. else:
  707. skipped_idxs.append(i)
  708. i += 1
  709. # Process year/month/day
  710. year, month, day = ymd.resolve_ymd(yearfirst, dayfirst)
  711. res.century_specified = ymd.century_specified
  712. res.year = year
  713. res.month = month
  714. res.day = day
  715. except (IndexError, ValueError):
  716. return None, None
  717. if not info.validate(res):
  718. return None, None
  719. if fuzzy_with_tokens:
  720. skipped_tokens = self._recombine_skipped(l, skipped_idxs)
  721. return res, tuple(skipped_tokens)
  722. else:
  723. return res, None
  724. def _parse_numeric_token(self, tokens, idx, info, ymd, res, fuzzy):
  725. # Token is a number
  726. value_repr = tokens[idx]
  727. try:
  728. value = self._to_decimal(value_repr)
  729. except Exception as e:
  730. six.raise_from(ValueError('Unknown numeric token'), e)
  731. len_li = len(value_repr)
  732. len_l = len(tokens)
  733. if (len(ymd) == 3 and len_li in (2, 4) and
  734. res.hour is None and
  735. (idx + 1 >= len_l or
  736. (tokens[idx + 1] != ':' and
  737. info.hms(tokens[idx + 1]) is None))):
  738. # 19990101T23[59]
  739. s = tokens[idx]
  740. res.hour = int(s[:2])
  741. if len_li == 4:
  742. res.minute = int(s[2:])
  743. elif len_li == 6 or (len_li > 6 and tokens[idx].find('.') == 6):
  744. # YYMMDD or HHMMSS[.ss]
  745. s = tokens[idx]
  746. if not ymd and '.' not in tokens[idx]:
  747. ymd.append(s[:2])
  748. ymd.append(s[2:4])
  749. ymd.append(s[4:])
  750. else:
  751. # 19990101T235959[.59]
  752. # TODO: Check if res attributes already set.
  753. res.hour = int(s[:2])
  754. res.minute = int(s[2:4])
  755. res.second, res.microsecond = self._parsems(s[4:])
  756. elif len_li in (8, 12, 14):
  757. # YYYYMMDD
  758. s = tokens[idx]
  759. ymd.append(s[:4], 'Y')
  760. ymd.append(s[4:6])
  761. ymd.append(s[6:8])
  762. if len_li > 8:
  763. res.hour = int(s[8:10])
  764. res.minute = int(s[10:12])
  765. if len_li > 12:
  766. res.second = int(s[12:])
  767. elif self._find_hms_idx(idx, tokens, info, allow_jump=True) is not None:
  768. # HH[ ]h or MM[ ]m or SS[.ss][ ]s
  769. hms_idx = self._find_hms_idx(idx, tokens, info, allow_jump=True)
  770. (idx, hms) = self._parse_hms(idx, tokens, info, hms_idx)
  771. if hms is not None:
  772. # TODO: checking that hour/minute/second are not
  773. # already set?
  774. self._assign_hms(res, value_repr, hms)
  775. elif idx + 2 < len_l and tokens[idx + 1] == ':':
  776. # HH:MM[:SS[.ss]]
  777. res.hour = int(value)
  778. value = self._to_decimal(tokens[idx + 2]) # TODO: try/except for this?
  779. (res.minute, res.second) = self._parse_min_sec(value)
  780. if idx + 4 < len_l and tokens[idx + 3] == ':':
  781. res.second, res.microsecond = self._parsems(tokens[idx + 4])
  782. idx += 2
  783. idx += 2
  784. elif idx + 1 < len_l and tokens[idx + 1] in ('-', '/', '.'):
  785. sep = tokens[idx + 1]
  786. ymd.append(value_repr)
  787. if idx + 2 < len_l and not info.jump(tokens[idx + 2]):
  788. if tokens[idx + 2].isdigit():
  789. # 01-01[-01]
  790. ymd.append(tokens[idx + 2])
  791. else:
  792. # 01-Jan[-01]
  793. value = info.month(tokens[idx + 2])
  794. if value is not None:
  795. ymd.append(value, 'M')
  796. else:
  797. raise ValueError()
  798. if idx + 3 < len_l and tokens[idx + 3] == sep:
  799. # We have three members
  800. value = info.month(tokens[idx + 4])
  801. if value is not None:
  802. ymd.append(value, 'M')
  803. else:
  804. ymd.append(tokens[idx + 4])
  805. idx += 2
  806. idx += 1
  807. idx += 1
  808. elif idx + 1 >= len_l or info.jump(tokens[idx + 1]):
  809. if idx + 2 < len_l and info.ampm(tokens[idx + 2]) is not None:
  810. # 12 am
  811. hour = int(value)
  812. res.hour = self._adjust_ampm(hour, info.ampm(tokens[idx + 2]))
  813. idx += 1
  814. else:
  815. # Year, month or day
  816. ymd.append(value)
  817. idx += 1
  818. elif info.ampm(tokens[idx + 1]) is not None and (0 <= value < 24):
  819. # 12am
  820. hour = int(value)
  821. res.hour = self._adjust_ampm(hour, info.ampm(tokens[idx + 1]))
  822. idx += 1
  823. elif ymd.could_be_day(value):
  824. ymd.append(value)
  825. elif not fuzzy:
  826. raise ValueError()
  827. return idx
  828. def _find_hms_idx(self, idx, tokens, info, allow_jump):
  829. len_l = len(tokens)
  830. if idx+1 < len_l and info.hms(tokens[idx+1]) is not None:
  831. # There is an "h", "m", or "s" label following this token. We take
  832. # assign the upcoming label to the current token.
  833. # e.g. the "12" in 12h"
  834. hms_idx = idx + 1
  835. elif (allow_jump and idx+2 < len_l and tokens[idx+1] == ' ' and
  836. info.hms(tokens[idx+2]) is not None):
  837. # There is a space and then an "h", "m", or "s" label.
  838. # e.g. the "12" in "12 h"
  839. hms_idx = idx + 2
  840. elif idx > 0 and info.hms(tokens[idx-1]) is not None:
  841. # There is a "h", "m", or "s" preceeding this token. Since neither
  842. # of the previous cases was hit, there is no label following this
  843. # token, so we use the previous label.
  844. # e.g. the "04" in "12h04"
  845. hms_idx = idx-1
  846. elif (1 < idx == len_l-1 and tokens[idx-1] == ' ' and
  847. info.hms(tokens[idx-2]) is not None):
  848. # If we are looking at the final token, we allow for a
  849. # backward-looking check to skip over a space.
  850. # TODO: Are we sure this is the right condition here?
  851. hms_idx = idx - 2
  852. else:
  853. hms_idx = None
  854. return hms_idx
  855. def _assign_hms(self, res, value_repr, hms):
  856. # See GH issue #427, fixing float rounding
  857. value = self._to_decimal(value_repr)
  858. if hms == 0:
  859. # Hour
  860. res.hour = int(value)
  861. if value % 1:
  862. res.minute = int(60*(value % 1))
  863. elif hms == 1:
  864. (res.minute, res.second) = self._parse_min_sec(value)
  865. elif hms == 2:
  866. (res.second, res.microsecond) = self._parsems(value_repr)
  867. def _could_be_tzname(self, hour, tzname, tzoffset, token):
  868. return (hour is not None and
  869. tzname is None and
  870. tzoffset is None and
  871. len(token) <= 5 and
  872. all(x in string.ascii_uppercase for x in token))
  873. def _ampm_valid(self, hour, ampm, fuzzy):
  874. """
  875. For fuzzy parsing, 'a' or 'am' (both valid English words)
  876. may erroneously trigger the AM/PM flag. Deal with that
  877. here.
  878. """
  879. val_is_ampm = True
  880. # If there's already an AM/PM flag, this one isn't one.
  881. if fuzzy and ampm is not None:
  882. val_is_ampm = False
  883. # If AM/PM is found and hour is not, raise a ValueError
  884. if hour is None:
  885. if fuzzy:
  886. val_is_ampm = False
  887. else:
  888. raise ValueError('No hour specified with AM or PM flag.')
  889. elif not 0 <= hour <= 12:
  890. # If AM/PM is found, it's a 12 hour clock, so raise
  891. # an error for invalid range
  892. if fuzzy:
  893. val_is_ampm = False
  894. else:
  895. raise ValueError('Invalid hour specified for 12-hour clock.')
  896. return val_is_ampm
  897. def _adjust_ampm(self, hour, ampm):
  898. if hour < 12 and ampm == 1:
  899. hour += 12
  900. elif hour == 12 and ampm == 0:
  901. hour = 0
  902. return hour
  903. def _parse_min_sec(self, value):
  904. # TODO: Every usage of this function sets res.second to the return
  905. # value. Are there any cases where second will be returned as None and
  906. # we *dont* want to set res.second = None?
  907. minute = int(value)
  908. second = None
  909. sec_remainder = value % 1
  910. if sec_remainder:
  911. second = int(60 * sec_remainder)
  912. return (minute, second)
  913. def _parsems(self, value):
  914. """Parse a I[.F] seconds value into (seconds, microseconds)."""
  915. if "." not in value:
  916. return int(value), 0
  917. else:
  918. i, f = value.split(".")
  919. return int(i), int(f.ljust(6, "0")[:6])
  920. def _parse_hms(self, idx, tokens, info, hms_idx):
  921. # TODO: Is this going to admit a lot of false-positives for when we
  922. # just happen to have digits and "h", "m" or "s" characters in non-date
  923. # text? I guess hex hashes won't have that problem, but there's plenty
  924. # of random junk out there.
  925. if hms_idx is None:
  926. hms = None
  927. new_idx = idx
  928. elif hms_idx > idx:
  929. hms = info.hms(tokens[hms_idx])
  930. new_idx = hms_idx
  931. else:
  932. # Looking backwards, increment one.
  933. hms = info.hms(tokens[hms_idx]) + 1
  934. new_idx = idx
  935. return (new_idx, hms)
  936. def _recombine_skipped(self, tokens, skipped_idxs):
  937. """
  938. >>> tokens = ["foo", " ", "bar", " ", "19June2000", "baz"]
  939. >>> skipped_idxs = [0, 1, 2, 5]
  940. >>> _recombine_skipped(tokens, skipped_idxs)
  941. ["foo bar", "baz"]
  942. """
  943. skipped_tokens = []
  944. for i, idx in enumerate(sorted(skipped_idxs)):
  945. if i > 0 and idx - 1 == skipped_idxs[i - 1]:
  946. skipped_tokens[-1] = skipped_tokens[-1] + tokens[idx]
  947. else:
  948. skipped_tokens.append(tokens[idx])
  949. return skipped_tokens
  950. def _build_tzinfo(self, tzinfos, tzname, tzoffset):
  951. if callable(tzinfos):
  952. tzdata = tzinfos(tzname, tzoffset)
  953. else:
  954. tzdata = tzinfos.get(tzname)
  955. # handle case where tzinfo is paased an options that returns None
  956. # eg tzinfos = {'BRST' : None}
  957. if isinstance(tzdata, datetime.tzinfo) or tzdata is None:
  958. tzinfo = tzdata
  959. elif isinstance(tzdata, text_type):
  960. tzinfo = tz.tzstr(tzdata)
  961. elif isinstance(tzdata, integer_types):
  962. tzinfo = tz.tzoffset(tzname, tzdata)
  963. return tzinfo
  964. def _build_tzaware(self, naive, res, tzinfos):
  965. if (callable(tzinfos) or (tzinfos and res.tzname in tzinfos)):
  966. tzinfo = self._build_tzinfo(tzinfos, res.tzname, res.tzoffset)
  967. aware = naive.replace(tzinfo=tzinfo)
  968. aware = self._assign_tzname(aware, res.tzname)
  969. elif res.tzname and res.tzname in time.tzname:
  970. aware = naive.replace(tzinfo=tz.tzlocal())
  971. # Handle ambiguous local datetime
  972. aware = self._assign_tzname(aware, res.tzname)
  973. # This is mostly relevant for winter GMT zones parsed in the UK
  974. if (aware.tzname() != res.tzname and
  975. res.tzname in self.info.UTCZONE):
  976. aware = aware.replace(tzinfo=tz.tzutc())
  977. elif res.tzoffset == 0:
  978. aware = naive.replace(tzinfo=tz.tzutc())
  979. elif res.tzoffset:
  980. aware = naive.replace(tzinfo=tz.tzoffset(res.tzname, res.tzoffset))
  981. elif not res.tzname and not res.tzoffset:
  982. # i.e. no timezone information was found.
  983. aware = naive
  984. elif res.tzname:
  985. # tz-like string was parsed but we don't know what to do
  986. # with it
  987. warnings.warn("tzname {tzname} identified but not understood. "
  988. "Pass `tzinfos` argument in order to correctly "
  989. "return a timezone-aware datetime. In a future "
  990. "version, this will raise an "
  991. "exception.".format(tzname=res.tzname),
  992. category=UnknownTimezoneWarning)
  993. aware = naive
  994. return aware
  995. def _build_naive(self, res, default):
  996. repl = {}
  997. for attr in ("year", "month", "day", "hour",
  998. "minute", "second", "microsecond"):
  999. value = getattr(res, attr)
  1000. if value is not None:
  1001. repl[attr] = value
  1002. if 'day' not in repl:
  1003. # If the default day exceeds the last day of the month, fall back
  1004. # to the end of the month.
  1005. cyear = default.year if res.year is None else res.year
  1006. cmonth = default.month if res.month is None else res.month
  1007. cday = default.day if res.day is None else res.day
  1008. if cday > monthrange(cyear, cmonth)[1]:
  1009. repl['day'] = monthrange(cyear, cmonth)[1]
  1010. naive = default.replace(**repl)
  1011. if res.weekday is not None and not res.day:
  1012. naive = naive + relativedelta.relativedelta(weekday=res.weekday)
  1013. return naive
  1014. def _assign_tzname(self, dt, tzname):
  1015. if dt.tzname() != tzname:
  1016. new_dt = tz.enfold(dt, fold=1)
  1017. if new_dt.tzname() == tzname:
  1018. return new_dt
  1019. return dt
  1020. def _to_decimal(self, val):
  1021. try:
  1022. decimal_value = Decimal(val)
  1023. # See GH 662, edge case, infinite value should not be converted via `_to_decimal`
  1024. if not decimal_value.is_finite():
  1025. raise ValueError("Converted decimal value is infinite or NaN")
  1026. except Exception as e:
  1027. msg = "Could not convert %s to decimal" % val
  1028. six.raise_from(ValueError(msg), e)
  1029. else:
  1030. return decimal_value
  1031. DEFAULTPARSER = parser()
  1032. def parse(timestr, parserinfo=None, **kwargs):
  1033. """
  1034. Parse a string in one of the supported formats, using the
  1035. ``parserinfo`` parameters.
  1036. :param timestr:
  1037. A string containing a date/time stamp.
  1038. :param parserinfo:
  1039. A :class:`parserinfo` object containing parameters for the parser.
  1040. If ``None``, the default arguments to the :class:`parserinfo`
  1041. constructor are used.
  1042. The ``**kwargs`` parameter takes the following keyword arguments:
  1043. :param default:
  1044. The default datetime object, if this is a datetime object and not
  1045. ``None``, elements specified in ``timestr`` replace elements in the
  1046. default object.
  1047. :param ignoretz:
  1048. If set ``True``, time zones in parsed strings are ignored and a naive
  1049. :class:`datetime` object is returned.
  1050. :param tzinfos:
  1051. Additional time zone names / aliases which may be present in the
  1052. string. This argument maps time zone names (and optionally offsets
  1053. from those time zones) to time zones. This parameter can be a
  1054. dictionary with timezone aliases mapping time zone names to time
  1055. zones or a function taking two parameters (``tzname`` and
  1056. ``tzoffset``) and returning a time zone.
  1057. The timezones to which the names are mapped can be an integer
  1058. offset from UTC in seconds or a :class:`tzinfo` object.
  1059. .. doctest::
  1060. :options: +NORMALIZE_WHITESPACE
  1061. >>> from dateutil.parser import parse
  1062. >>> from dateutil.tz import gettz
  1063. >>> tzinfos = {"BRST": -7200, "CST": gettz("America/Chicago")}
  1064. >>> parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos)
  1065. datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -7200))
  1066. >>> parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos)
  1067. datetime.datetime(2012, 1, 19, 17, 21,
  1068. tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago'))
  1069. This parameter is ignored if ``ignoretz`` is set.
  1070. :param dayfirst:
  1071. Whether to interpret the first value in an ambiguous 3-integer date
  1072. (e.g. 01/05/09) as the day (``True``) or month (``False``). If
  1073. ``yearfirst`` is set to ``True``, this distinguishes between YDM and
  1074. YMD. If set to ``None``, this value is retrieved from the current
  1075. :class:`parserinfo` object (which itself defaults to ``False``).
  1076. :param yearfirst:
  1077. Whether to interpret the first value in an ambiguous 3-integer date
  1078. (e.g. 01/05/09) as the year. If ``True``, the first number is taken to
  1079. be the year, otherwise the last number is taken to be the year. If
  1080. this is set to ``None``, the value is retrieved from the current
  1081. :class:`parserinfo` object (which itself defaults to ``False``).
  1082. :param fuzzy:
  1083. Whether to allow fuzzy parsing, allowing for string like "Today is
  1084. January 1, 2047 at 8:21:00AM".
  1085. :param fuzzy_with_tokens:
  1086. If ``True``, ``fuzzy`` is automatically set to True, and the parser
  1087. will return a tuple where the first element is the parsed
  1088. :class:`datetime.datetime` datetimestamp and the second element is
  1089. a tuple containing the portions of the string which were ignored:
  1090. .. doctest::
  1091. >>> from dateutil.parser import parse
  1092. >>> parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True)
  1093. (datetime.datetime(2047, 1, 1, 8, 21), (u'Today is ', u' ', u'at '))
  1094. :return:
  1095. Returns a :class:`datetime.datetime` object or, if the
  1096. ``fuzzy_with_tokens`` option is ``True``, returns a tuple, the
  1097. first element being a :class:`datetime.datetime` object, the second
  1098. a tuple containing the fuzzy tokens.
  1099. :raises ValueError:
  1100. Raised for invalid or unknown string format, if the provided
  1101. :class:`tzinfo` is not in a valid format, or if an invalid date
  1102. would be created.
  1103. :raises OverflowError:
  1104. Raised if the parsed date exceeds the largest valid C integer on
  1105. your system.
  1106. """
  1107. if parserinfo:
  1108. return parser(parserinfo).parse(timestr, **kwargs)
  1109. else:
  1110. return DEFAULTPARSER.parse(timestr, **kwargs)
  1111. class _tzparser(object):
  1112. class _result(_resultbase):
  1113. __slots__ = ["stdabbr", "stdoffset", "dstabbr", "dstoffset",
  1114. "start", "end"]
  1115. class _attr(_resultbase):
  1116. __slots__ = ["month", "week", "weekday",
  1117. "yday", "jyday", "day", "time"]
  1118. def __repr__(self):
  1119. return self._repr("")
  1120. def __init__(self):
  1121. _resultbase.__init__(self)
  1122. self.start = self._attr()
  1123. self.end = self._attr()
  1124. def parse(self, tzstr):
  1125. res = self._result()
  1126. l = [x for x in re.split(r'([,:.]|[a-zA-Z]+|[0-9]+)',tzstr) if x]
  1127. used_idxs = list()
  1128. try:
  1129. len_l = len(l)
  1130. i = 0
  1131. while i < len_l:
  1132. # BRST+3[BRDT[+2]]
  1133. j = i
  1134. while j < len_l and not [x for x in l[j]
  1135. if x in "0123456789:,-+"]:
  1136. j += 1
  1137. if j != i:
  1138. if not res.stdabbr:
  1139. offattr = "stdoffset"
  1140. res.stdabbr = "".join(l[i:j])
  1141. else:
  1142. offattr = "dstoffset"
  1143. res.dstabbr = "".join(l[i:j])
  1144. for ii in range(j):
  1145. used_idxs.append(ii)
  1146. i = j
  1147. if (i < len_l and (l[i] in ('+', '-') or l[i][0] in
  1148. "0123456789")):
  1149. if l[i] in ('+', '-'):
  1150. # Yes, that's right. See the TZ variable
  1151. # documentation.
  1152. signal = (1, -1)[l[i] == '+']
  1153. used_idxs.append(i)
  1154. i += 1
  1155. else:
  1156. signal = -1
  1157. len_li = len(l[i])
  1158. if len_li == 4:
  1159. # -0300
  1160. setattr(res, offattr, (int(l[i][:2]) * 3600 +
  1161. int(l[i][2:]) * 60) * signal)
  1162. elif i + 1 < len_l and l[i + 1] == ':':
  1163. # -03:00
  1164. setattr(res, offattr,
  1165. (int(l[i]) * 3600 +
  1166. int(l[i + 2]) * 60) * signal)
  1167. used_idxs.append(i)
  1168. i += 2
  1169. elif len_li <= 2:
  1170. # -[0]3
  1171. setattr(res, offattr,
  1172. int(l[i][:2]) * 3600 * signal)
  1173. else:
  1174. return None
  1175. used_idxs.append(i)
  1176. i += 1
  1177. if res.dstabbr:
  1178. break
  1179. else:
  1180. break
  1181. if i < len_l:
  1182. for j in range(i, len_l):
  1183. if l[j] == ';':
  1184. l[j] = ','
  1185. assert l[i] == ','
  1186. i += 1
  1187. if i >= len_l:
  1188. pass
  1189. elif (8 <= l.count(',') <= 9 and
  1190. not [y for x in l[i:] if x != ','
  1191. for y in x if y not in "0123456789+-"]):
  1192. # GMT0BST,3,0,30,3600,10,0,26,7200[,3600]
  1193. for x in (res.start, res.end):
  1194. x.month = int(l[i])
  1195. used_idxs.append(i)
  1196. i += 2
  1197. if l[i] == '-':
  1198. value = int(l[i + 1]) * -1
  1199. used_idxs.append(i)
  1200. i += 1
  1201. else:
  1202. value = int(l[i])
  1203. used_idxs.append(i)
  1204. i += 2
  1205. if value:
  1206. x.week = value
  1207. x.weekday = (int(l[i]) - 1) % 7
  1208. else:
  1209. x.day = int(l[i])
  1210. used_idxs.append(i)
  1211. i += 2
  1212. x.time = int(l[i])
  1213. used_idxs.append(i)
  1214. i += 2
  1215. if i < len_l:
  1216. if l[i] in ('-', '+'):
  1217. signal = (-1, 1)[l[i] == "+"]
  1218. used_idxs.append(i)
  1219. i += 1
  1220. else:
  1221. signal = 1
  1222. used_idxs.append(i)
  1223. res.dstoffset = (res.stdoffset + int(l[i]) * signal)
  1224. # This was a made-up format that is not in normal use
  1225. warn(('Parsed time zone "%s"' % tzstr) +
  1226. 'is in a non-standard dateutil-specific format, which ' +
  1227. 'is now deprecated; support for parsing this format ' +
  1228. 'will be removed in future versions. It is recommended ' +
  1229. 'that you switch to a standard format like the GNU ' +
  1230. 'TZ variable format.', tz.DeprecatedTzFormatWarning)
  1231. elif (l.count(',') == 2 and l[i:].count('/') <= 2 and
  1232. not [y for x in l[i:] if x not in (',', '/', 'J', 'M',
  1233. '.', '-', ':')
  1234. for y in x if y not in "0123456789"]):
  1235. for x in (res.start, res.end):
  1236. if l[i] == 'J':
  1237. # non-leap year day (1 based)
  1238. used_idxs.append(i)
  1239. i += 1
  1240. x.jyday = int(l[i])
  1241. elif l[i] == 'M':
  1242. # month[-.]week[-.]weekday
  1243. used_idxs.append(i)
  1244. i += 1
  1245. x.month = int(l[i])
  1246. used_idxs.append(i)
  1247. i += 1
  1248. assert l[i] in ('-', '.')
  1249. used_idxs.append(i)
  1250. i += 1
  1251. x.week = int(l[i])
  1252. if x.week == 5:
  1253. x.week = -1
  1254. used_idxs.append(i)
  1255. i += 1
  1256. assert l[i] in ('-', '.')
  1257. used_idxs.append(i)
  1258. i += 1
  1259. x.weekday = (int(l[i]) - 1) % 7
  1260. else:
  1261. # year day (zero based)
  1262. x.yday = int(l[i]) + 1
  1263. used_idxs.append(i)
  1264. i += 1
  1265. if i < len_l and l[i] == '/':
  1266. used_idxs.append(i)
  1267. i += 1
  1268. # start time
  1269. len_li = len(l[i])
  1270. if len_li == 4:
  1271. # -0300
  1272. x.time = (int(l[i][:2]) * 3600 +
  1273. int(l[i][2:]) * 60)
  1274. elif i + 1 < len_l and l[i + 1] == ':':
  1275. # -03:00
  1276. x.time = int(l[i]) * 3600 + int(l[i + 2]) * 60
  1277. used_idxs.append(i)
  1278. i += 2
  1279. if i + 1 < len_l and l[i + 1] == ':':
  1280. used_idxs.append(i)
  1281. i += 2
  1282. x.time += int(l[i])
  1283. elif len_li <= 2:
  1284. # -[0]3
  1285. x.time = (int(l[i][:2]) * 3600)
  1286. else:
  1287. return None
  1288. used_idxs.append(i)
  1289. i += 1
  1290. assert i == len_l or l[i] == ','
  1291. i += 1
  1292. assert i >= len_l
  1293. except (IndexError, ValueError, AssertionError):
  1294. return None
  1295. unused_idxs = set(range(len_l)).difference(used_idxs)
  1296. res.any_unused_tokens = not {l[n] for n in unused_idxs}.issubset({",",":"})
  1297. return res
  1298. DEFAULTTZPARSER = _tzparser()
  1299. def _parsetz(tzstr):
  1300. return DEFAULTTZPARSER.parse(tzstr)
  1301. class UnknownTimezoneWarning(RuntimeWarning):
  1302. """Raised when the parser finds a timezone it cannot parse into a tzinfo"""
  1303. # vim:ts=4:sw=4:et