_pydatetime.py 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645
  1. """Concrete date/time and related types.
  2. See http://www.iana.org/time-zones/repository/tz-link.html for
  3. time zone and DST data sources.
  4. """
  5. __all__ = ("date", "datetime", "time", "timedelta", "timezone", "tzinfo",
  6. "MINYEAR", "MAXYEAR", "UTC")
  7. import time as _time
  8. import math as _math
  9. import sys
  10. from operator import index as _index
  11. def _cmp(x, y):
  12. return 0 if x == y else 1 if x > y else -1
  13. def _get_class_module(self):
  14. module_name = self.__class__.__module__
  15. if module_name == '_pydatetime':
  16. return 'datetime'
  17. else:
  18. return module_name
  19. MINYEAR = 1
  20. MAXYEAR = 9999
  21. _MAXORDINAL = 3652059 # date.max.toordinal()
  22. # Utility functions, adapted from Python's Demo/classes/Dates.py, which
  23. # also assumes the current Gregorian calendar indefinitely extended in
  24. # both directions. Difference: Dates.py calls January 1 of year 0 day
  25. # number 1. The code here calls January 1 of year 1 day number 1. This is
  26. # to match the definition of the "proleptic Gregorian" calendar in Dershowitz
  27. # and Reingold's "Calendrical Calculations", where it's the base calendar
  28. # for all computations. See the book for algorithms for converting between
  29. # proleptic Gregorian ordinals and many other calendar systems.
  30. # -1 is a placeholder for indexing purposes.
  31. _DAYS_IN_MONTH = [-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  32. _DAYS_BEFORE_MONTH = [-1] # -1 is a placeholder for indexing purposes.
  33. dbm = 0
  34. for dim in _DAYS_IN_MONTH[1:]:
  35. _DAYS_BEFORE_MONTH.append(dbm)
  36. dbm += dim
  37. del dbm, dim
  38. def _is_leap(year):
  39. "year -> 1 if leap year, else 0."
  40. return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
  41. def _days_before_year(year):
  42. "year -> number of days before January 1st of year."
  43. y = year - 1
  44. return y*365 + y//4 - y//100 + y//400
  45. def _days_in_month(year, month):
  46. "year, month -> number of days in that month in that year."
  47. assert 1 <= month <= 12, month
  48. if month == 2 and _is_leap(year):
  49. return 29
  50. return _DAYS_IN_MONTH[month]
  51. def _days_before_month(year, month):
  52. "year, month -> number of days in year preceding first day of month."
  53. assert 1 <= month <= 12, 'month must be in 1..12'
  54. return _DAYS_BEFORE_MONTH[month] + (month > 2 and _is_leap(year))
  55. def _ymd2ord(year, month, day):
  56. "year, month, day -> ordinal, considering 01-Jan-0001 as day 1."
  57. assert 1 <= month <= 12, 'month must be in 1..12'
  58. dim = _days_in_month(year, month)
  59. assert 1 <= day <= dim, ('day must be in 1..%d' % dim)
  60. return (_days_before_year(year) +
  61. _days_before_month(year, month) +
  62. day)
  63. _DI400Y = _days_before_year(401) # number of days in 400 years
  64. _DI100Y = _days_before_year(101) # " " " " 100 "
  65. _DI4Y = _days_before_year(5) # " " " " 4 "
  66. # A 4-year cycle has an extra leap day over what we'd get from pasting
  67. # together 4 single years.
  68. assert _DI4Y == 4 * 365 + 1
  69. # Similarly, a 400-year cycle has an extra leap day over what we'd get from
  70. # pasting together 4 100-year cycles.
  71. assert _DI400Y == 4 * _DI100Y + 1
  72. # OTOH, a 100-year cycle has one fewer leap day than we'd get from
  73. # pasting together 25 4-year cycles.
  74. assert _DI100Y == 25 * _DI4Y - 1
  75. def _ord2ymd(n):
  76. "ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."
  77. # n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
  78. # repeats exactly every 400 years. The basic strategy is to find the
  79. # closest 400-year boundary at or before n, then work with the offset
  80. # from that boundary to n. Life is much clearer if we subtract 1 from
  81. # n first -- then the values of n at 400-year boundaries are exactly
  82. # those divisible by _DI400Y:
  83. #
  84. # D M Y n n-1
  85. # -- --- ---- ---------- ----------------
  86. # 31 Dec -400 -_DI400Y -_DI400Y -1
  87. # 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary
  88. # ...
  89. # 30 Dec 000 -1 -2
  90. # 31 Dec 000 0 -1
  91. # 1 Jan 001 1 0 400-year boundary
  92. # 2 Jan 001 2 1
  93. # 3 Jan 001 3 2
  94. # ...
  95. # 31 Dec 400 _DI400Y _DI400Y -1
  96. # 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
  97. n -= 1
  98. n400, n = divmod(n, _DI400Y)
  99. year = n400 * 400 + 1 # ..., -399, 1, 401, ...
  100. # Now n is the (non-negative) offset, in days, from January 1 of year, to
  101. # the desired date. Now compute how many 100-year cycles precede n.
  102. # Note that it's possible for n100 to equal 4! In that case 4 full
  103. # 100-year cycles precede the desired day, which implies the desired
  104. # day is December 31 at the end of a 400-year cycle.
  105. n100, n = divmod(n, _DI100Y)
  106. # Now compute how many 4-year cycles precede it.
  107. n4, n = divmod(n, _DI4Y)
  108. # And now how many single years. Again n1 can be 4, and again meaning
  109. # that the desired day is December 31 at the end of the 4-year cycle.
  110. n1, n = divmod(n, 365)
  111. year += n100 * 100 + n4 * 4 + n1
  112. if n1 == 4 or n100 == 4:
  113. assert n == 0
  114. return year-1, 12, 31
  115. # Now the year is correct, and n is the offset from January 1. We find
  116. # the month via an estimate that's either exact or one too large.
  117. leapyear = n1 == 3 and (n4 != 24 or n100 == 3)
  118. assert leapyear == _is_leap(year)
  119. month = (n + 50) >> 5
  120. preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 and leapyear)
  121. if preceding > n: # estimate is too large
  122. month -= 1
  123. preceding -= _DAYS_IN_MONTH[month] + (month == 2 and leapyear)
  124. n -= preceding
  125. assert 0 <= n < _days_in_month(year, month)
  126. # Now the year and month are correct, and n is the offset from the
  127. # start of that month: we're done!
  128. return year, month, n+1
  129. # Month and day names. For localized versions, see the calendar module.
  130. _MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  131. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
  132. _DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
  133. def _build_struct_time(y, m, d, hh, mm, ss, dstflag):
  134. wday = (_ymd2ord(y, m, d) + 6) % 7
  135. dnum = _days_before_month(y, m) + d
  136. return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag))
  137. def _format_time(hh, mm, ss, us, timespec='auto'):
  138. specs = {
  139. 'hours': '{:02d}',
  140. 'minutes': '{:02d}:{:02d}',
  141. 'seconds': '{:02d}:{:02d}:{:02d}',
  142. 'milliseconds': '{:02d}:{:02d}:{:02d}.{:03d}',
  143. 'microseconds': '{:02d}:{:02d}:{:02d}.{:06d}'
  144. }
  145. if timespec == 'auto':
  146. # Skip trailing microseconds when us==0.
  147. timespec = 'microseconds' if us else 'seconds'
  148. elif timespec == 'milliseconds':
  149. us //= 1000
  150. try:
  151. fmt = specs[timespec]
  152. except KeyError:
  153. raise ValueError('Unknown timespec value')
  154. else:
  155. return fmt.format(hh, mm, ss, us)
  156. def _format_offset(off, sep=':'):
  157. s = ''
  158. if off is not None:
  159. if off.days < 0:
  160. sign = "-"
  161. off = -off
  162. else:
  163. sign = "+"
  164. hh, mm = divmod(off, timedelta(hours=1))
  165. mm, ss = divmod(mm, timedelta(minutes=1))
  166. s += "%s%02d%s%02d" % (sign, hh, sep, mm)
  167. if ss or ss.microseconds:
  168. s += "%s%02d" % (sep, ss.seconds)
  169. if ss.microseconds:
  170. s += '.%06d' % ss.microseconds
  171. return s
  172. # Correctly substitute for %z and %Z escapes in strftime formats.
  173. def _wrap_strftime(object, format, timetuple):
  174. # Don't call utcoffset() or tzname() unless actually needed.
  175. freplace = None # the string to use for %f
  176. zreplace = None # the string to use for %z
  177. colonzreplace = None # the string to use for %:z
  178. Zreplace = None # the string to use for %Z
  179. # Scan format for %z, %:z and %Z escapes, replacing as needed.
  180. newformat = []
  181. push = newformat.append
  182. i, n = 0, len(format)
  183. while i < n:
  184. ch = format[i]
  185. i += 1
  186. if ch == '%':
  187. if i < n:
  188. ch = format[i]
  189. i += 1
  190. if ch == 'f':
  191. if freplace is None:
  192. freplace = '%06d' % getattr(object,
  193. 'microsecond', 0)
  194. newformat.append(freplace)
  195. elif ch == 'z':
  196. if zreplace is None:
  197. if hasattr(object, "utcoffset"):
  198. zreplace = _format_offset(object.utcoffset(), sep="")
  199. else:
  200. zreplace = ""
  201. assert '%' not in zreplace
  202. newformat.append(zreplace)
  203. elif ch == ':':
  204. if i < n:
  205. ch2 = format[i]
  206. i += 1
  207. if ch2 == 'z':
  208. if colonzreplace is None:
  209. if hasattr(object, "utcoffset"):
  210. colonzreplace = _format_offset(object.utcoffset(), sep=":")
  211. else:
  212. colonzreplace = ""
  213. assert '%' not in colonzreplace
  214. newformat.append(colonzreplace)
  215. else:
  216. push('%')
  217. push(ch)
  218. push(ch2)
  219. elif ch == 'Z':
  220. if Zreplace is None:
  221. Zreplace = ""
  222. if hasattr(object, "tzname"):
  223. s = object.tzname()
  224. if s is not None:
  225. # strftime is going to have at this: escape %
  226. Zreplace = s.replace('%', '%%')
  227. newformat.append(Zreplace)
  228. else:
  229. push('%')
  230. push(ch)
  231. else:
  232. push('%')
  233. else:
  234. push(ch)
  235. newformat = "".join(newformat)
  236. return _time.strftime(newformat, timetuple)
  237. # Helpers for parsing the result of isoformat()
  238. def _is_ascii_digit(c):
  239. return c in "0123456789"
  240. def _find_isoformat_datetime_separator(dtstr):
  241. # See the comment in _datetimemodule.c:_find_isoformat_datetime_separator
  242. len_dtstr = len(dtstr)
  243. if len_dtstr == 7:
  244. return 7
  245. assert len_dtstr > 7
  246. date_separator = "-"
  247. week_indicator = "W"
  248. if dtstr[4] == date_separator:
  249. if dtstr[5] == week_indicator:
  250. if len_dtstr < 8:
  251. raise ValueError("Invalid ISO string")
  252. if len_dtstr > 8 and dtstr[8] == date_separator:
  253. if len_dtstr == 9:
  254. raise ValueError("Invalid ISO string")
  255. if len_dtstr > 10 and _is_ascii_digit(dtstr[10]):
  256. # This is as far as we need to resolve the ambiguity for
  257. # the moment - if we have YYYY-Www-##, the separator is
  258. # either a hyphen at 8 or a number at 10.
  259. #
  260. # We'll assume it's a hyphen at 8 because it's way more
  261. # likely that someone will use a hyphen as a separator than
  262. # a number, but at this point it's really best effort
  263. # because this is an extension of the spec anyway.
  264. # TODO(pganssle): Document this
  265. return 8
  266. return 10
  267. else:
  268. # YYYY-Www (8)
  269. return 8
  270. else:
  271. # YYYY-MM-DD (10)
  272. return 10
  273. else:
  274. if dtstr[4] == week_indicator:
  275. # YYYYWww (7) or YYYYWwwd (8)
  276. idx = 7
  277. while idx < len_dtstr:
  278. if not _is_ascii_digit(dtstr[idx]):
  279. break
  280. idx += 1
  281. if idx < 9:
  282. return idx
  283. if idx % 2 == 0:
  284. # If the index of the last number is even, it's YYYYWwwd
  285. return 7
  286. else:
  287. return 8
  288. else:
  289. # YYYYMMDD (8)
  290. return 8
  291. def _parse_isoformat_date(dtstr):
  292. # It is assumed that this is an ASCII-only string of lengths 7, 8 or 10,
  293. # see the comment on Modules/_datetimemodule.c:_find_isoformat_datetime_separator
  294. assert len(dtstr) in (7, 8, 10)
  295. year = int(dtstr[0:4])
  296. has_sep = dtstr[4] == '-'
  297. pos = 4 + has_sep
  298. if dtstr[pos:pos + 1] == "W":
  299. # YYYY-?Www-?D?
  300. pos += 1
  301. weekno = int(dtstr[pos:pos + 2])
  302. pos += 2
  303. dayno = 1
  304. if len(dtstr) > pos:
  305. if (dtstr[pos:pos + 1] == '-') != has_sep:
  306. raise ValueError("Inconsistent use of dash separator")
  307. pos += has_sep
  308. dayno = int(dtstr[pos:pos + 1])
  309. return list(_isoweek_to_gregorian(year, weekno, dayno))
  310. else:
  311. month = int(dtstr[pos:pos + 2])
  312. pos += 2
  313. if (dtstr[pos:pos + 1] == "-") != has_sep:
  314. raise ValueError("Inconsistent use of dash separator")
  315. pos += has_sep
  316. day = int(dtstr[pos:pos + 2])
  317. return [year, month, day]
  318. _FRACTION_CORRECTION = [100000, 10000, 1000, 100, 10]
  319. def _parse_hh_mm_ss_ff(tstr):
  320. # Parses things of the form HH[:?MM[:?SS[{.,}fff[fff]]]]
  321. len_str = len(tstr)
  322. time_comps = [0, 0, 0, 0]
  323. pos = 0
  324. for comp in range(0, 3):
  325. if (len_str - pos) < 2:
  326. raise ValueError("Incomplete time component")
  327. time_comps[comp] = int(tstr[pos:pos+2])
  328. pos += 2
  329. next_char = tstr[pos:pos+1]
  330. if comp == 0:
  331. has_sep = next_char == ':'
  332. if not next_char or comp >= 2:
  333. break
  334. if has_sep and next_char != ':':
  335. raise ValueError("Invalid time separator: %c" % next_char)
  336. pos += has_sep
  337. if pos < len_str:
  338. if tstr[pos] not in '.,':
  339. raise ValueError("Invalid microsecond component")
  340. else:
  341. pos += 1
  342. len_remainder = len_str - pos
  343. if len_remainder >= 6:
  344. to_parse = 6
  345. else:
  346. to_parse = len_remainder
  347. time_comps[3] = int(tstr[pos:(pos+to_parse)])
  348. if to_parse < 6:
  349. time_comps[3] *= _FRACTION_CORRECTION[to_parse-1]
  350. if (len_remainder > to_parse
  351. and not all(map(_is_ascii_digit, tstr[(pos+to_parse):]))):
  352. raise ValueError("Non-digit values in unparsed fraction")
  353. return time_comps
  354. def _parse_isoformat_time(tstr):
  355. # Format supported is HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]
  356. len_str = len(tstr)
  357. if len_str < 2:
  358. raise ValueError("Isoformat time too short")
  359. # This is equivalent to re.search('[+-Z]', tstr), but faster
  360. tz_pos = (tstr.find('-') + 1 or tstr.find('+') + 1 or tstr.find('Z') + 1)
  361. timestr = tstr[:tz_pos-1] if tz_pos > 0 else tstr
  362. time_comps = _parse_hh_mm_ss_ff(timestr)
  363. tzi = None
  364. if tz_pos == len_str and tstr[-1] == 'Z':
  365. tzi = timezone.utc
  366. elif tz_pos > 0:
  367. tzstr = tstr[tz_pos:]
  368. # Valid time zone strings are:
  369. # HH len: 2
  370. # HHMM len: 4
  371. # HH:MM len: 5
  372. # HHMMSS len: 6
  373. # HHMMSS.f+ len: 7+
  374. # HH:MM:SS len: 8
  375. # HH:MM:SS.f+ len: 10+
  376. if len(tzstr) in (0, 1, 3):
  377. raise ValueError("Malformed time zone string")
  378. tz_comps = _parse_hh_mm_ss_ff(tzstr)
  379. if all(x == 0 for x in tz_comps):
  380. tzi = timezone.utc
  381. else:
  382. tzsign = -1 if tstr[tz_pos - 1] == '-' else 1
  383. td = timedelta(hours=tz_comps[0], minutes=tz_comps[1],
  384. seconds=tz_comps[2], microseconds=tz_comps[3])
  385. tzi = timezone(tzsign * td)
  386. time_comps.append(tzi)
  387. return time_comps
  388. # tuple[int, int, int] -> tuple[int, int, int] version of date.fromisocalendar
  389. def _isoweek_to_gregorian(year, week, day):
  390. # Year is bounded this way because 9999-12-31 is (9999, 52, 5)
  391. if not MINYEAR <= year <= MAXYEAR:
  392. raise ValueError(f"Year is out of range: {year}")
  393. if not 0 < week < 53:
  394. out_of_range = True
  395. if week == 53:
  396. # ISO years have 53 weeks in them on years starting with a
  397. # Thursday and leap years starting on a Wednesday
  398. first_weekday = _ymd2ord(year, 1, 1) % 7
  399. if (first_weekday == 4 or (first_weekday == 3 and
  400. _is_leap(year))):
  401. out_of_range = False
  402. if out_of_range:
  403. raise ValueError(f"Invalid week: {week}")
  404. if not 0 < day < 8:
  405. raise ValueError(f"Invalid weekday: {day} (range is [1, 7])")
  406. # Now compute the offset from (Y, 1, 1) in days:
  407. day_offset = (week - 1) * 7 + (day - 1)
  408. # Calculate the ordinal day for monday, week 1
  409. day_1 = _isoweek1monday(year)
  410. ord_day = day_1 + day_offset
  411. return _ord2ymd(ord_day)
  412. # Just raise TypeError if the arg isn't None or a string.
  413. def _check_tzname(name):
  414. if name is not None and not isinstance(name, str):
  415. raise TypeError("tzinfo.tzname() must return None or string, "
  416. "not '%s'" % type(name))
  417. # name is the offset-producing method, "utcoffset" or "dst".
  418. # offset is what it returned.
  419. # If offset isn't None or timedelta, raises TypeError.
  420. # If offset is None, returns None.
  421. # Else offset is checked for being in range.
  422. # If it is, its integer value is returned. Else ValueError is raised.
  423. def _check_utc_offset(name, offset):
  424. assert name in ("utcoffset", "dst")
  425. if offset is None:
  426. return
  427. if not isinstance(offset, timedelta):
  428. raise TypeError("tzinfo.%s() must return None "
  429. "or timedelta, not '%s'" % (name, type(offset)))
  430. if not -timedelta(1) < offset < timedelta(1):
  431. raise ValueError("%s()=%s, must be strictly between "
  432. "-timedelta(hours=24) and timedelta(hours=24)" %
  433. (name, offset))
  434. def _check_date_fields(year, month, day):
  435. year = _index(year)
  436. month = _index(month)
  437. day = _index(day)
  438. if not MINYEAR <= year <= MAXYEAR:
  439. raise ValueError('year must be in %d..%d' % (MINYEAR, MAXYEAR), year)
  440. if not 1 <= month <= 12:
  441. raise ValueError('month must be in 1..12', month)
  442. dim = _days_in_month(year, month)
  443. if not 1 <= day <= dim:
  444. raise ValueError('day must be in 1..%d' % dim, day)
  445. return year, month, day
  446. def _check_time_fields(hour, minute, second, microsecond, fold):
  447. hour = _index(hour)
  448. minute = _index(minute)
  449. second = _index(second)
  450. microsecond = _index(microsecond)
  451. if not 0 <= hour <= 23:
  452. raise ValueError('hour must be in 0..23', hour)
  453. if not 0 <= minute <= 59:
  454. raise ValueError('minute must be in 0..59', minute)
  455. if not 0 <= second <= 59:
  456. raise ValueError('second must be in 0..59', second)
  457. if not 0 <= microsecond <= 999999:
  458. raise ValueError('microsecond must be in 0..999999', microsecond)
  459. if fold not in (0, 1):
  460. raise ValueError('fold must be either 0 or 1', fold)
  461. return hour, minute, second, microsecond, fold
  462. def _check_tzinfo_arg(tz):
  463. if tz is not None and not isinstance(tz, tzinfo):
  464. raise TypeError("tzinfo argument must be None or of a tzinfo subclass")
  465. def _cmperror(x, y):
  466. raise TypeError("can't compare '%s' to '%s'" % (
  467. type(x).__name__, type(y).__name__))
  468. def _divide_and_round(a, b):
  469. """divide a by b and round result to the nearest integer
  470. When the ratio is exactly half-way between two integers,
  471. the even integer is returned.
  472. """
  473. # Based on the reference implementation for divmod_near
  474. # in Objects/longobject.c.
  475. q, r = divmod(a, b)
  476. # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
  477. # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
  478. # positive, 2 * r < b if b negative.
  479. r *= 2
  480. greater_than_half = r > b if b > 0 else r < b
  481. if greater_than_half or r == b and q % 2 == 1:
  482. q += 1
  483. return q
  484. class timedelta:
  485. """Represent the difference between two datetime objects.
  486. Supported operators:
  487. - add, subtract timedelta
  488. - unary plus, minus, abs
  489. - compare to timedelta
  490. - multiply, divide by int
  491. In addition, datetime supports subtraction of two datetime objects
  492. returning a timedelta, and addition or subtraction of a datetime
  493. and a timedelta giving a datetime.
  494. Representation: (days, seconds, microseconds).
  495. """
  496. # The representation of (days, seconds, microseconds) was chosen
  497. # arbitrarily; the exact rationale originally specified in the docstring
  498. # was "Because I felt like it."
  499. __slots__ = '_days', '_seconds', '_microseconds', '_hashcode'
  500. def __new__(cls, days=0, seconds=0, microseconds=0,
  501. milliseconds=0, minutes=0, hours=0, weeks=0):
  502. # Doing this efficiently and accurately in C is going to be difficult
  503. # and error-prone, due to ubiquitous overflow possibilities, and that
  504. # C double doesn't have enough bits of precision to represent
  505. # microseconds over 10K years faithfully. The code here tries to make
  506. # explicit where go-fast assumptions can be relied on, in order to
  507. # guide the C implementation; it's way more convoluted than speed-
  508. # ignoring auto-overflow-to-long idiomatic Python could be.
  509. # XXX Check that all inputs are ints or floats.
  510. # Final values, all integer.
  511. # s and us fit in 32-bit signed ints; d isn't bounded.
  512. d = s = us = 0
  513. # Normalize everything to days, seconds, microseconds.
  514. days += weeks*7
  515. seconds += minutes*60 + hours*3600
  516. microseconds += milliseconds*1000
  517. # Get rid of all fractions, and normalize s and us.
  518. # Take a deep breath <wink>.
  519. if isinstance(days, float):
  520. dayfrac, days = _math.modf(days)
  521. daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.*3600.))
  522. assert daysecondswhole == int(daysecondswhole) # can't overflow
  523. s = int(daysecondswhole)
  524. assert days == int(days)
  525. d = int(days)
  526. else:
  527. daysecondsfrac = 0.0
  528. d = days
  529. assert isinstance(daysecondsfrac, float)
  530. assert abs(daysecondsfrac) <= 1.0
  531. assert isinstance(d, int)
  532. assert abs(s) <= 24 * 3600
  533. # days isn't referenced again before redefinition
  534. if isinstance(seconds, float):
  535. secondsfrac, seconds = _math.modf(seconds)
  536. assert seconds == int(seconds)
  537. seconds = int(seconds)
  538. secondsfrac += daysecondsfrac
  539. assert abs(secondsfrac) <= 2.0
  540. else:
  541. secondsfrac = daysecondsfrac
  542. # daysecondsfrac isn't referenced again
  543. assert isinstance(secondsfrac, float)
  544. assert abs(secondsfrac) <= 2.0
  545. assert isinstance(seconds, int)
  546. days, seconds = divmod(seconds, 24*3600)
  547. d += days
  548. s += int(seconds) # can't overflow
  549. assert isinstance(s, int)
  550. assert abs(s) <= 2 * 24 * 3600
  551. # seconds isn't referenced again before redefinition
  552. usdouble = secondsfrac * 1e6
  553. assert abs(usdouble) < 2.1e6 # exact value not critical
  554. # secondsfrac isn't referenced again
  555. if isinstance(microseconds, float):
  556. microseconds = round(microseconds + usdouble)
  557. seconds, microseconds = divmod(microseconds, 1000000)
  558. days, seconds = divmod(seconds, 24*3600)
  559. d += days
  560. s += seconds
  561. else:
  562. microseconds = int(microseconds)
  563. seconds, microseconds = divmod(microseconds, 1000000)
  564. days, seconds = divmod(seconds, 24*3600)
  565. d += days
  566. s += seconds
  567. microseconds = round(microseconds + usdouble)
  568. assert isinstance(s, int)
  569. assert isinstance(microseconds, int)
  570. assert abs(s) <= 3 * 24 * 3600
  571. assert abs(microseconds) < 3.1e6
  572. # Just a little bit of carrying possible for microseconds and seconds.
  573. seconds, us = divmod(microseconds, 1000000)
  574. s += seconds
  575. days, s = divmod(s, 24*3600)
  576. d += days
  577. assert isinstance(d, int)
  578. assert isinstance(s, int) and 0 <= s < 24*3600
  579. assert isinstance(us, int) and 0 <= us < 1000000
  580. if abs(d) > 999999999:
  581. raise OverflowError("timedelta # of days is too large: %d" % d)
  582. self = object.__new__(cls)
  583. self._days = d
  584. self._seconds = s
  585. self._microseconds = us
  586. self._hashcode = -1
  587. return self
  588. def __repr__(self):
  589. args = []
  590. if self._days:
  591. args.append("days=%d" % self._days)
  592. if self._seconds:
  593. args.append("seconds=%d" % self._seconds)
  594. if self._microseconds:
  595. args.append("microseconds=%d" % self._microseconds)
  596. if not args:
  597. args.append('0')
  598. return "%s.%s(%s)" % (_get_class_module(self),
  599. self.__class__.__qualname__,
  600. ', '.join(args))
  601. def __str__(self):
  602. mm, ss = divmod(self._seconds, 60)
  603. hh, mm = divmod(mm, 60)
  604. s = "%d:%02d:%02d" % (hh, mm, ss)
  605. if self._days:
  606. def plural(n):
  607. return n, abs(n) != 1 and "s" or ""
  608. s = ("%d day%s, " % plural(self._days)) + s
  609. if self._microseconds:
  610. s = s + ".%06d" % self._microseconds
  611. return s
  612. def total_seconds(self):
  613. """Total seconds in the duration."""
  614. return ((self.days * 86400 + self.seconds) * 10**6 +
  615. self.microseconds) / 10**6
  616. # Read-only field accessors
  617. @property
  618. def days(self):
  619. """days"""
  620. return self._days
  621. @property
  622. def seconds(self):
  623. """seconds"""
  624. return self._seconds
  625. @property
  626. def microseconds(self):
  627. """microseconds"""
  628. return self._microseconds
  629. def __add__(self, other):
  630. if isinstance(other, timedelta):
  631. # for CPython compatibility, we cannot use
  632. # our __class__ here, but need a real timedelta
  633. return timedelta(self._days + other._days,
  634. self._seconds + other._seconds,
  635. self._microseconds + other._microseconds)
  636. return NotImplemented
  637. __radd__ = __add__
  638. def __sub__(self, other):
  639. if isinstance(other, timedelta):
  640. # for CPython compatibility, we cannot use
  641. # our __class__ here, but need a real timedelta
  642. return timedelta(self._days - other._days,
  643. self._seconds - other._seconds,
  644. self._microseconds - other._microseconds)
  645. return NotImplemented
  646. def __rsub__(self, other):
  647. if isinstance(other, timedelta):
  648. return -self + other
  649. return NotImplemented
  650. def __neg__(self):
  651. # for CPython compatibility, we cannot use
  652. # our __class__ here, but need a real timedelta
  653. return timedelta(-self._days,
  654. -self._seconds,
  655. -self._microseconds)
  656. def __pos__(self):
  657. return self
  658. def __abs__(self):
  659. if self._days < 0:
  660. return -self
  661. else:
  662. return self
  663. def __mul__(self, other):
  664. if isinstance(other, int):
  665. # for CPython compatibility, we cannot use
  666. # our __class__ here, but need a real timedelta
  667. return timedelta(self._days * other,
  668. self._seconds * other,
  669. self._microseconds * other)
  670. if isinstance(other, float):
  671. usec = self._to_microseconds()
  672. a, b = other.as_integer_ratio()
  673. return timedelta(0, 0, _divide_and_round(usec * a, b))
  674. return NotImplemented
  675. __rmul__ = __mul__
  676. def _to_microseconds(self):
  677. return ((self._days * (24*3600) + self._seconds) * 1000000 +
  678. self._microseconds)
  679. def __floordiv__(self, other):
  680. if not isinstance(other, (int, timedelta)):
  681. return NotImplemented
  682. usec = self._to_microseconds()
  683. if isinstance(other, timedelta):
  684. return usec // other._to_microseconds()
  685. if isinstance(other, int):
  686. return timedelta(0, 0, usec // other)
  687. def __truediv__(self, other):
  688. if not isinstance(other, (int, float, timedelta)):
  689. return NotImplemented
  690. usec = self._to_microseconds()
  691. if isinstance(other, timedelta):
  692. return usec / other._to_microseconds()
  693. if isinstance(other, int):
  694. return timedelta(0, 0, _divide_and_round(usec, other))
  695. if isinstance(other, float):
  696. a, b = other.as_integer_ratio()
  697. return timedelta(0, 0, _divide_and_round(b * usec, a))
  698. def __mod__(self, other):
  699. if isinstance(other, timedelta):
  700. r = self._to_microseconds() % other._to_microseconds()
  701. return timedelta(0, 0, r)
  702. return NotImplemented
  703. def __divmod__(self, other):
  704. if isinstance(other, timedelta):
  705. q, r = divmod(self._to_microseconds(),
  706. other._to_microseconds())
  707. return q, timedelta(0, 0, r)
  708. return NotImplemented
  709. # Comparisons of timedelta objects with other.
  710. def __eq__(self, other):
  711. if isinstance(other, timedelta):
  712. return self._cmp(other) == 0
  713. else:
  714. return NotImplemented
  715. def __le__(self, other):
  716. if isinstance(other, timedelta):
  717. return self._cmp(other) <= 0
  718. else:
  719. return NotImplemented
  720. def __lt__(self, other):
  721. if isinstance(other, timedelta):
  722. return self._cmp(other) < 0
  723. else:
  724. return NotImplemented
  725. def __ge__(self, other):
  726. if isinstance(other, timedelta):
  727. return self._cmp(other) >= 0
  728. else:
  729. return NotImplemented
  730. def __gt__(self, other):
  731. if isinstance(other, timedelta):
  732. return self._cmp(other) > 0
  733. else:
  734. return NotImplemented
  735. def _cmp(self, other):
  736. assert isinstance(other, timedelta)
  737. return _cmp(self._getstate(), other._getstate())
  738. def __hash__(self):
  739. if self._hashcode == -1:
  740. self._hashcode = hash(self._getstate())
  741. return self._hashcode
  742. def __bool__(self):
  743. return (self._days != 0 or
  744. self._seconds != 0 or
  745. self._microseconds != 0)
  746. # Pickle support.
  747. def _getstate(self):
  748. return (self._days, self._seconds, self._microseconds)
  749. def __reduce__(self):
  750. return (self.__class__, self._getstate())
  751. timedelta.min = timedelta(-999999999)
  752. timedelta.max = timedelta(days=999999999, hours=23, minutes=59, seconds=59,
  753. microseconds=999999)
  754. timedelta.resolution = timedelta(microseconds=1)
  755. class date:
  756. """Concrete date type.
  757. Constructors:
  758. __new__()
  759. fromtimestamp()
  760. today()
  761. fromordinal()
  762. Operators:
  763. __repr__, __str__
  764. __eq__, __le__, __lt__, __ge__, __gt__, __hash__
  765. __add__, __radd__, __sub__ (add/radd only with timedelta arg)
  766. Methods:
  767. timetuple()
  768. toordinal()
  769. weekday()
  770. isoweekday(), isocalendar(), isoformat()
  771. ctime()
  772. strftime()
  773. Properties (readonly):
  774. year, month, day
  775. """
  776. __slots__ = '_year', '_month', '_day', '_hashcode'
  777. def __new__(cls, year, month=None, day=None):
  778. """Constructor.
  779. Arguments:
  780. year, month, day (required, base 1)
  781. """
  782. if (month is None and
  783. isinstance(year, (bytes, str)) and len(year) == 4 and
  784. 1 <= ord(year[2:3]) <= 12):
  785. # Pickle support
  786. if isinstance(year, str):
  787. try:
  788. year = year.encode('latin1')
  789. except UnicodeEncodeError:
  790. # More informative error message.
  791. raise ValueError(
  792. "Failed to encode latin1 string when unpickling "
  793. "a date object. "
  794. "pickle.load(data, encoding='latin1') is assumed.")
  795. self = object.__new__(cls)
  796. self.__setstate(year)
  797. self._hashcode = -1
  798. return self
  799. year, month, day = _check_date_fields(year, month, day)
  800. self = object.__new__(cls)
  801. self._year = year
  802. self._month = month
  803. self._day = day
  804. self._hashcode = -1
  805. return self
  806. # Additional constructors
  807. @classmethod
  808. def fromtimestamp(cls, t):
  809. "Construct a date from a POSIX timestamp (like time.time())."
  810. if t is None:
  811. raise TypeError("'NoneType' object cannot be interpreted as an integer")
  812. y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t)
  813. return cls(y, m, d)
  814. @classmethod
  815. def today(cls):
  816. "Construct a date from time.time()."
  817. t = _time.time()
  818. return cls.fromtimestamp(t)
  819. @classmethod
  820. def fromordinal(cls, n):
  821. """Construct a date from a proleptic Gregorian ordinal.
  822. January 1 of year 1 is day 1. Only the year, month and day are
  823. non-zero in the result.
  824. """
  825. y, m, d = _ord2ymd(n)
  826. return cls(y, m, d)
  827. @classmethod
  828. def fromisoformat(cls, date_string):
  829. """Construct a date from a string in ISO 8601 format."""
  830. if not isinstance(date_string, str):
  831. raise TypeError('fromisoformat: argument must be str')
  832. if len(date_string) not in (7, 8, 10):
  833. raise ValueError(f'Invalid isoformat string: {date_string!r}')
  834. try:
  835. return cls(*_parse_isoformat_date(date_string))
  836. except Exception:
  837. raise ValueError(f'Invalid isoformat string: {date_string!r}')
  838. @classmethod
  839. def fromisocalendar(cls, year, week, day):
  840. """Construct a date from the ISO year, week number and weekday.
  841. This is the inverse of the date.isocalendar() function"""
  842. return cls(*_isoweek_to_gregorian(year, week, day))
  843. # Conversions to string
  844. def __repr__(self):
  845. """Convert to formal string, for repr().
  846. >>> d = date(2010, 1, 1)
  847. >>> repr(d)
  848. 'datetime.date(2010, 1, 1)'
  849. """
  850. return "%s.%s(%d, %d, %d)" % (_get_class_module(self),
  851. self.__class__.__qualname__,
  852. self._year,
  853. self._month,
  854. self._day)
  855. # XXX These shouldn't depend on time.localtime(), because that
  856. # clips the usable dates to [1970 .. 2038). At least ctime() is
  857. # easily done without using strftime() -- that's better too because
  858. # strftime("%c", ...) is locale specific.
  859. def ctime(self):
  860. "Return ctime() style string."
  861. weekday = self.toordinal() % 7 or 7
  862. return "%s %s %2d 00:00:00 %04d" % (
  863. _DAYNAMES[weekday],
  864. _MONTHNAMES[self._month],
  865. self._day, self._year)
  866. def strftime(self, format):
  867. """
  868. Format using strftime().
  869. Example: "%d/%m/%Y, %H:%M:%S"
  870. """
  871. return _wrap_strftime(self, format, self.timetuple())
  872. def __format__(self, fmt):
  873. if not isinstance(fmt, str):
  874. raise TypeError("must be str, not %s" % type(fmt).__name__)
  875. if len(fmt) != 0:
  876. return self.strftime(fmt)
  877. return str(self)
  878. def isoformat(self):
  879. """Return the date formatted according to ISO.
  880. This is 'YYYY-MM-DD'.
  881. References:
  882. - http://www.w3.org/TR/NOTE-datetime
  883. - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
  884. """
  885. return "%04d-%02d-%02d" % (self._year, self._month, self._day)
  886. __str__ = isoformat
  887. # Read-only field accessors
  888. @property
  889. def year(self):
  890. """year (1-9999)"""
  891. return self._year
  892. @property
  893. def month(self):
  894. """month (1-12)"""
  895. return self._month
  896. @property
  897. def day(self):
  898. """day (1-31)"""
  899. return self._day
  900. # Standard conversions, __eq__, __le__, __lt__, __ge__, __gt__,
  901. # __hash__ (and helpers)
  902. def timetuple(self):
  903. "Return local time tuple compatible with time.localtime()."
  904. return _build_struct_time(self._year, self._month, self._day,
  905. 0, 0, 0, -1)
  906. def toordinal(self):
  907. """Return proleptic Gregorian ordinal for the year, month and day.
  908. January 1 of year 1 is day 1. Only the year, month and day values
  909. contribute to the result.
  910. """
  911. return _ymd2ord(self._year, self._month, self._day)
  912. def replace(self, year=None, month=None, day=None):
  913. """Return a new date with new values for the specified fields."""
  914. if year is None:
  915. year = self._year
  916. if month is None:
  917. month = self._month
  918. if day is None:
  919. day = self._day
  920. return type(self)(year, month, day)
  921. # Comparisons of date objects with other.
  922. def __eq__(self, other):
  923. if isinstance(other, date):
  924. return self._cmp(other) == 0
  925. return NotImplemented
  926. def __le__(self, other):
  927. if isinstance(other, date):
  928. return self._cmp(other) <= 0
  929. return NotImplemented
  930. def __lt__(self, other):
  931. if isinstance(other, date):
  932. return self._cmp(other) < 0
  933. return NotImplemented
  934. def __ge__(self, other):
  935. if isinstance(other, date):
  936. return self._cmp(other) >= 0
  937. return NotImplemented
  938. def __gt__(self, other):
  939. if isinstance(other, date):
  940. return self._cmp(other) > 0
  941. return NotImplemented
  942. def _cmp(self, other):
  943. assert isinstance(other, date)
  944. y, m, d = self._year, self._month, self._day
  945. y2, m2, d2 = other._year, other._month, other._day
  946. return _cmp((y, m, d), (y2, m2, d2))
  947. def __hash__(self):
  948. "Hash."
  949. if self._hashcode == -1:
  950. self._hashcode = hash(self._getstate())
  951. return self._hashcode
  952. # Computations
  953. def __add__(self, other):
  954. "Add a date to a timedelta."
  955. if isinstance(other, timedelta):
  956. o = self.toordinal() + other.days
  957. if 0 < o <= _MAXORDINAL:
  958. return type(self).fromordinal(o)
  959. raise OverflowError("result out of range")
  960. return NotImplemented
  961. __radd__ = __add__
  962. def __sub__(self, other):
  963. """Subtract two dates, or a date and a timedelta."""
  964. if isinstance(other, timedelta):
  965. return self + timedelta(-other.days)
  966. if isinstance(other, date):
  967. days1 = self.toordinal()
  968. days2 = other.toordinal()
  969. return timedelta(days1 - days2)
  970. return NotImplemented
  971. def weekday(self):
  972. "Return day of the week, where Monday == 0 ... Sunday == 6."
  973. return (self.toordinal() + 6) % 7
  974. # Day-of-the-week and week-of-the-year, according to ISO
  975. def isoweekday(self):
  976. "Return day of the week, where Monday == 1 ... Sunday == 7."
  977. # 1-Jan-0001 is a Monday
  978. return self.toordinal() % 7 or 7
  979. def isocalendar(self):
  980. """Return a named tuple containing ISO year, week number, and weekday.
  981. The first ISO week of the year is the (Mon-Sun) week
  982. containing the year's first Thursday; everything else derives
  983. from that.
  984. The first week is 1; Monday is 1 ... Sunday is 7.
  985. ISO calendar algorithm taken from
  986. http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
  987. (used with permission)
  988. """
  989. year = self._year
  990. week1monday = _isoweek1monday(year)
  991. today = _ymd2ord(self._year, self._month, self._day)
  992. # Internally, week and day have origin 0
  993. week, day = divmod(today - week1monday, 7)
  994. if week < 0:
  995. year -= 1
  996. week1monday = _isoweek1monday(year)
  997. week, day = divmod(today - week1monday, 7)
  998. elif week >= 52:
  999. if today >= _isoweek1monday(year+1):
  1000. year += 1
  1001. week = 0
  1002. return _IsoCalendarDate(year, week+1, day+1)
  1003. # Pickle support.
  1004. def _getstate(self):
  1005. yhi, ylo = divmod(self._year, 256)
  1006. return bytes([yhi, ylo, self._month, self._day]),
  1007. def __setstate(self, string):
  1008. yhi, ylo, self._month, self._day = string
  1009. self._year = yhi * 256 + ylo
  1010. def __reduce__(self):
  1011. return (self.__class__, self._getstate())
  1012. _date_class = date # so functions w/ args named "date" can get at the class
  1013. date.min = date(1, 1, 1)
  1014. date.max = date(9999, 12, 31)
  1015. date.resolution = timedelta(days=1)
  1016. class tzinfo:
  1017. """Abstract base class for time zone info classes.
  1018. Subclasses must override the tzname(), utcoffset() and dst() methods.
  1019. """
  1020. __slots__ = ()
  1021. def tzname(self, dt):
  1022. "datetime -> string name of time zone."
  1023. raise NotImplementedError("tzinfo subclass must override tzname()")
  1024. def utcoffset(self, dt):
  1025. "datetime -> timedelta, positive for east of UTC, negative for west of UTC"
  1026. raise NotImplementedError("tzinfo subclass must override utcoffset()")
  1027. def dst(self, dt):
  1028. """datetime -> DST offset as timedelta, positive for east of UTC.
  1029. Return 0 if DST not in effect. utcoffset() must include the DST
  1030. offset.
  1031. """
  1032. raise NotImplementedError("tzinfo subclass must override dst()")
  1033. def fromutc(self, dt):
  1034. "datetime in UTC -> datetime in local time."
  1035. if not isinstance(dt, datetime):
  1036. raise TypeError("fromutc() requires a datetime argument")
  1037. if dt.tzinfo is not self:
  1038. raise ValueError("dt.tzinfo is not self")
  1039. dtoff = dt.utcoffset()
  1040. if dtoff is None:
  1041. raise ValueError("fromutc() requires a non-None utcoffset() "
  1042. "result")
  1043. # See the long comment block at the end of this file for an
  1044. # explanation of this algorithm.
  1045. dtdst = dt.dst()
  1046. if dtdst is None:
  1047. raise ValueError("fromutc() requires a non-None dst() result")
  1048. delta = dtoff - dtdst
  1049. if delta:
  1050. dt += delta
  1051. dtdst = dt.dst()
  1052. if dtdst is None:
  1053. raise ValueError("fromutc(): dt.dst gave inconsistent "
  1054. "results; cannot convert")
  1055. return dt + dtdst
  1056. # Pickle support.
  1057. def __reduce__(self):
  1058. getinitargs = getattr(self, "__getinitargs__", None)
  1059. if getinitargs:
  1060. args = getinitargs()
  1061. else:
  1062. args = ()
  1063. return (self.__class__, args, self.__getstate__())
  1064. class IsoCalendarDate(tuple):
  1065. def __new__(cls, year, week, weekday, /):
  1066. return super().__new__(cls, (year, week, weekday))
  1067. @property
  1068. def year(self):
  1069. return self[0]
  1070. @property
  1071. def week(self):
  1072. return self[1]
  1073. @property
  1074. def weekday(self):
  1075. return self[2]
  1076. def __reduce__(self):
  1077. # This code is intended to pickle the object without making the
  1078. # class public. See https://bugs.python.org/msg352381
  1079. return (tuple, (tuple(self),))
  1080. def __repr__(self):
  1081. return (f'{self.__class__.__name__}'
  1082. f'(year={self[0]}, week={self[1]}, weekday={self[2]})')
  1083. _IsoCalendarDate = IsoCalendarDate
  1084. del IsoCalendarDate
  1085. _tzinfo_class = tzinfo
  1086. class time:
  1087. """Time with time zone.
  1088. Constructors:
  1089. __new__()
  1090. Operators:
  1091. __repr__, __str__
  1092. __eq__, __le__, __lt__, __ge__, __gt__, __hash__
  1093. Methods:
  1094. strftime()
  1095. isoformat()
  1096. utcoffset()
  1097. tzname()
  1098. dst()
  1099. Properties (readonly):
  1100. hour, minute, second, microsecond, tzinfo, fold
  1101. """
  1102. __slots__ = '_hour', '_minute', '_second', '_microsecond', '_tzinfo', '_hashcode', '_fold'
  1103. def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0):
  1104. """Constructor.
  1105. Arguments:
  1106. hour, minute (required)
  1107. second, microsecond (default to zero)
  1108. tzinfo (default to None)
  1109. fold (keyword only, default to zero)
  1110. """
  1111. if (isinstance(hour, (bytes, str)) and len(hour) == 6 and
  1112. ord(hour[0:1])&0x7F < 24):
  1113. # Pickle support
  1114. if isinstance(hour, str):
  1115. try:
  1116. hour = hour.encode('latin1')
  1117. except UnicodeEncodeError:
  1118. # More informative error message.
  1119. raise ValueError(
  1120. "Failed to encode latin1 string when unpickling "
  1121. "a time object. "
  1122. "pickle.load(data, encoding='latin1') is assumed.")
  1123. self = object.__new__(cls)
  1124. self.__setstate(hour, minute or None)
  1125. self._hashcode = -1
  1126. return self
  1127. hour, minute, second, microsecond, fold = _check_time_fields(
  1128. hour, minute, second, microsecond, fold)
  1129. _check_tzinfo_arg(tzinfo)
  1130. self = object.__new__(cls)
  1131. self._hour = hour
  1132. self._minute = minute
  1133. self._second = second
  1134. self._microsecond = microsecond
  1135. self._tzinfo = tzinfo
  1136. self._hashcode = -1
  1137. self._fold = fold
  1138. return self
  1139. # Read-only field accessors
  1140. @property
  1141. def hour(self):
  1142. """hour (0-23)"""
  1143. return self._hour
  1144. @property
  1145. def minute(self):
  1146. """minute (0-59)"""
  1147. return self._minute
  1148. @property
  1149. def second(self):
  1150. """second (0-59)"""
  1151. return self._second
  1152. @property
  1153. def microsecond(self):
  1154. """microsecond (0-999999)"""
  1155. return self._microsecond
  1156. @property
  1157. def tzinfo(self):
  1158. """timezone info object"""
  1159. return self._tzinfo
  1160. @property
  1161. def fold(self):
  1162. return self._fold
  1163. # Standard conversions, __hash__ (and helpers)
  1164. # Comparisons of time objects with other.
  1165. def __eq__(self, other):
  1166. if isinstance(other, time):
  1167. return self._cmp(other, allow_mixed=True) == 0
  1168. else:
  1169. return NotImplemented
  1170. def __le__(self, other):
  1171. if isinstance(other, time):
  1172. return self._cmp(other) <= 0
  1173. else:
  1174. return NotImplemented
  1175. def __lt__(self, other):
  1176. if isinstance(other, time):
  1177. return self._cmp(other) < 0
  1178. else:
  1179. return NotImplemented
  1180. def __ge__(self, other):
  1181. if isinstance(other, time):
  1182. return self._cmp(other) >= 0
  1183. else:
  1184. return NotImplemented
  1185. def __gt__(self, other):
  1186. if isinstance(other, time):
  1187. return self._cmp(other) > 0
  1188. else:
  1189. return NotImplemented
  1190. def _cmp(self, other, allow_mixed=False):
  1191. assert isinstance(other, time)
  1192. mytz = self._tzinfo
  1193. ottz = other._tzinfo
  1194. myoff = otoff = None
  1195. if mytz is ottz:
  1196. base_compare = True
  1197. else:
  1198. myoff = self.utcoffset()
  1199. otoff = other.utcoffset()
  1200. base_compare = myoff == otoff
  1201. if base_compare:
  1202. return _cmp((self._hour, self._minute, self._second,
  1203. self._microsecond),
  1204. (other._hour, other._minute, other._second,
  1205. other._microsecond))
  1206. if myoff is None or otoff is None:
  1207. if allow_mixed:
  1208. return 2 # arbitrary non-zero value
  1209. else:
  1210. raise TypeError("cannot compare naive and aware times")
  1211. myhhmm = self._hour * 60 + self._minute - myoff//timedelta(minutes=1)
  1212. othhmm = other._hour * 60 + other._minute - otoff//timedelta(minutes=1)
  1213. return _cmp((myhhmm, self._second, self._microsecond),
  1214. (othhmm, other._second, other._microsecond))
  1215. def __hash__(self):
  1216. """Hash."""
  1217. if self._hashcode == -1:
  1218. if self.fold:
  1219. t = self.replace(fold=0)
  1220. else:
  1221. t = self
  1222. tzoff = t.utcoffset()
  1223. if not tzoff: # zero or None
  1224. self._hashcode = hash(t._getstate()[0])
  1225. else:
  1226. h, m = divmod(timedelta(hours=self.hour, minutes=self.minute) - tzoff,
  1227. timedelta(hours=1))
  1228. assert not m % timedelta(minutes=1), "whole minute"
  1229. m //= timedelta(minutes=1)
  1230. if 0 <= h < 24:
  1231. self._hashcode = hash(time(h, m, self.second, self.microsecond))
  1232. else:
  1233. self._hashcode = hash((h, m, self.second, self.microsecond))
  1234. return self._hashcode
  1235. # Conversion to string
  1236. def _tzstr(self):
  1237. """Return formatted timezone offset (+xx:xx) or an empty string."""
  1238. off = self.utcoffset()
  1239. return _format_offset(off)
  1240. def __repr__(self):
  1241. """Convert to formal string, for repr()."""
  1242. if self._microsecond != 0:
  1243. s = ", %d, %d" % (self._second, self._microsecond)
  1244. elif self._second != 0:
  1245. s = ", %d" % self._second
  1246. else:
  1247. s = ""
  1248. s= "%s.%s(%d, %d%s)" % (_get_class_module(self),
  1249. self.__class__.__qualname__,
  1250. self._hour, self._minute, s)
  1251. if self._tzinfo is not None:
  1252. assert s[-1:] == ")"
  1253. s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
  1254. if self._fold:
  1255. assert s[-1:] == ")"
  1256. s = s[:-1] + ", fold=1)"
  1257. return s
  1258. def isoformat(self, timespec='auto'):
  1259. """Return the time formatted according to ISO.
  1260. The full format is 'HH:MM:SS.mmmmmm+zz:zz'. By default, the fractional
  1261. part is omitted if self.microsecond == 0.
  1262. The optional argument timespec specifies the number of additional
  1263. terms of the time to include. Valid options are 'auto', 'hours',
  1264. 'minutes', 'seconds', 'milliseconds' and 'microseconds'.
  1265. """
  1266. s = _format_time(self._hour, self._minute, self._second,
  1267. self._microsecond, timespec)
  1268. tz = self._tzstr()
  1269. if tz:
  1270. s += tz
  1271. return s
  1272. __str__ = isoformat
  1273. @classmethod
  1274. def fromisoformat(cls, time_string):
  1275. """Construct a time from a string in one of the ISO 8601 formats."""
  1276. if not isinstance(time_string, str):
  1277. raise TypeError('fromisoformat: argument must be str')
  1278. # The spec actually requires that time-only ISO 8601 strings start with
  1279. # T, but the extended format allows this to be omitted as long as there
  1280. # is no ambiguity with date strings.
  1281. time_string = time_string.removeprefix('T')
  1282. try:
  1283. return cls(*_parse_isoformat_time(time_string))
  1284. except Exception:
  1285. raise ValueError(f'Invalid isoformat string: {time_string!r}')
  1286. def strftime(self, format):
  1287. """Format using strftime(). The date part of the timestamp passed
  1288. to underlying strftime should not be used.
  1289. """
  1290. # The year must be >= 1000 else Python's strftime implementation
  1291. # can raise a bogus exception.
  1292. timetuple = (1900, 1, 1,
  1293. self._hour, self._minute, self._second,
  1294. 0, 1, -1)
  1295. return _wrap_strftime(self, format, timetuple)
  1296. def __format__(self, fmt):
  1297. if not isinstance(fmt, str):
  1298. raise TypeError("must be str, not %s" % type(fmt).__name__)
  1299. if len(fmt) != 0:
  1300. return self.strftime(fmt)
  1301. return str(self)
  1302. # Timezone functions
  1303. def utcoffset(self):
  1304. """Return the timezone offset as timedelta, positive east of UTC
  1305. (negative west of UTC)."""
  1306. if self._tzinfo is None:
  1307. return None
  1308. offset = self._tzinfo.utcoffset(None)
  1309. _check_utc_offset("utcoffset", offset)
  1310. return offset
  1311. def tzname(self):
  1312. """Return the timezone name.
  1313. Note that the name is 100% informational -- there's no requirement that
  1314. it mean anything in particular. For example, "GMT", "UTC", "-500",
  1315. "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
  1316. """
  1317. if self._tzinfo is None:
  1318. return None
  1319. name = self._tzinfo.tzname(None)
  1320. _check_tzname(name)
  1321. return name
  1322. def dst(self):
  1323. """Return 0 if DST is not in effect, or the DST offset (as timedelta
  1324. positive eastward) if DST is in effect.
  1325. This is purely informational; the DST offset has already been added to
  1326. the UTC offset returned by utcoffset() if applicable, so there's no
  1327. need to consult dst() unless you're interested in displaying the DST
  1328. info.
  1329. """
  1330. if self._tzinfo is None:
  1331. return None
  1332. offset = self._tzinfo.dst(None)
  1333. _check_utc_offset("dst", offset)
  1334. return offset
  1335. def replace(self, hour=None, minute=None, second=None, microsecond=None,
  1336. tzinfo=True, *, fold=None):
  1337. """Return a new time with new values for the specified fields."""
  1338. if hour is None:
  1339. hour = self.hour
  1340. if minute is None:
  1341. minute = self.minute
  1342. if second is None:
  1343. second = self.second
  1344. if microsecond is None:
  1345. microsecond = self.microsecond
  1346. if tzinfo is True:
  1347. tzinfo = self.tzinfo
  1348. if fold is None:
  1349. fold = self._fold
  1350. return type(self)(hour, minute, second, microsecond, tzinfo, fold=fold)
  1351. # Pickle support.
  1352. def _getstate(self, protocol=3):
  1353. us2, us3 = divmod(self._microsecond, 256)
  1354. us1, us2 = divmod(us2, 256)
  1355. h = self._hour
  1356. if self._fold and protocol > 3:
  1357. h += 128
  1358. basestate = bytes([h, self._minute, self._second,
  1359. us1, us2, us3])
  1360. if self._tzinfo is None:
  1361. return (basestate,)
  1362. else:
  1363. return (basestate, self._tzinfo)
  1364. def __setstate(self, string, tzinfo):
  1365. if tzinfo is not None and not isinstance(tzinfo, _tzinfo_class):
  1366. raise TypeError("bad tzinfo state arg")
  1367. h, self._minute, self._second, us1, us2, us3 = string
  1368. if h > 127:
  1369. self._fold = 1
  1370. self._hour = h - 128
  1371. else:
  1372. self._fold = 0
  1373. self._hour = h
  1374. self._microsecond = (((us1 << 8) | us2) << 8) | us3
  1375. self._tzinfo = tzinfo
  1376. def __reduce_ex__(self, protocol):
  1377. return (self.__class__, self._getstate(protocol))
  1378. def __reduce__(self):
  1379. return self.__reduce_ex__(2)
  1380. _time_class = time # so functions w/ args named "time" can get at the class
  1381. time.min = time(0, 0, 0)
  1382. time.max = time(23, 59, 59, 999999)
  1383. time.resolution = timedelta(microseconds=1)
  1384. class datetime(date):
  1385. """datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
  1386. The year, month and day arguments are required. tzinfo may be None, or an
  1387. instance of a tzinfo subclass. The remaining arguments may be ints.
  1388. """
  1389. __slots__ = date.__slots__ + time.__slots__
  1390. def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0,
  1391. microsecond=0, tzinfo=None, *, fold=0):
  1392. if (isinstance(year, (bytes, str)) and len(year) == 10 and
  1393. 1 <= ord(year[2:3])&0x7F <= 12):
  1394. # Pickle support
  1395. if isinstance(year, str):
  1396. try:
  1397. year = bytes(year, 'latin1')
  1398. except UnicodeEncodeError:
  1399. # More informative error message.
  1400. raise ValueError(
  1401. "Failed to encode latin1 string when unpickling "
  1402. "a datetime object. "
  1403. "pickle.load(data, encoding='latin1') is assumed.")
  1404. self = object.__new__(cls)
  1405. self.__setstate(year, month)
  1406. self._hashcode = -1
  1407. return self
  1408. year, month, day = _check_date_fields(year, month, day)
  1409. hour, minute, second, microsecond, fold = _check_time_fields(
  1410. hour, minute, second, microsecond, fold)
  1411. _check_tzinfo_arg(tzinfo)
  1412. self = object.__new__(cls)
  1413. self._year = year
  1414. self._month = month
  1415. self._day = day
  1416. self._hour = hour
  1417. self._minute = minute
  1418. self._second = second
  1419. self._microsecond = microsecond
  1420. self._tzinfo = tzinfo
  1421. self._hashcode = -1
  1422. self._fold = fold
  1423. return self
  1424. # Read-only field accessors
  1425. @property
  1426. def hour(self):
  1427. """hour (0-23)"""
  1428. return self._hour
  1429. @property
  1430. def minute(self):
  1431. """minute (0-59)"""
  1432. return self._minute
  1433. @property
  1434. def second(self):
  1435. """second (0-59)"""
  1436. return self._second
  1437. @property
  1438. def microsecond(self):
  1439. """microsecond (0-999999)"""
  1440. return self._microsecond
  1441. @property
  1442. def tzinfo(self):
  1443. """timezone info object"""
  1444. return self._tzinfo
  1445. @property
  1446. def fold(self):
  1447. return self._fold
  1448. @classmethod
  1449. def _fromtimestamp(cls, t, utc, tz):
  1450. """Construct a datetime from a POSIX timestamp (like time.time()).
  1451. A timezone info object may be passed in as well.
  1452. """
  1453. frac, t = _math.modf(t)
  1454. us = round(frac * 1e6)
  1455. if us >= 1000000:
  1456. t += 1
  1457. us -= 1000000
  1458. elif us < 0:
  1459. t -= 1
  1460. us += 1000000
  1461. converter = _time.gmtime if utc else _time.localtime
  1462. y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
  1463. ss = min(ss, 59) # clamp out leap seconds if the platform has them
  1464. result = cls(y, m, d, hh, mm, ss, us, tz)
  1465. if tz is None and not utc:
  1466. # As of version 2015f max fold in IANA database is
  1467. # 23 hours at 1969-09-30 13:00:00 in Kwajalein.
  1468. # Let's probe 24 hours in the past to detect a transition:
  1469. max_fold_seconds = 24 * 3600
  1470. # On Windows localtime_s throws an OSError for negative values,
  1471. # thus we can't perform fold detection for values of time less
  1472. # than the max time fold. See comments in _datetimemodule's
  1473. # version of this method for more details.
  1474. if t < max_fold_seconds and sys.platform.startswith("win"):
  1475. return result
  1476. y, m, d, hh, mm, ss = converter(t - max_fold_seconds)[:6]
  1477. probe1 = cls(y, m, d, hh, mm, ss, us, tz)
  1478. trans = result - probe1 - timedelta(0, max_fold_seconds)
  1479. if trans.days < 0:
  1480. y, m, d, hh, mm, ss = converter(t + trans // timedelta(0, 1))[:6]
  1481. probe2 = cls(y, m, d, hh, mm, ss, us, tz)
  1482. if probe2 == result:
  1483. result._fold = 1
  1484. elif tz is not None:
  1485. result = tz.fromutc(result)
  1486. return result
  1487. @classmethod
  1488. def fromtimestamp(cls, timestamp, tz=None):
  1489. """Construct a datetime from a POSIX timestamp (like time.time()).
  1490. A timezone info object may be passed in as well.
  1491. """
  1492. _check_tzinfo_arg(tz)
  1493. return cls._fromtimestamp(timestamp, tz is not None, tz)
  1494. @classmethod
  1495. def utcfromtimestamp(cls, t):
  1496. """Construct a naive UTC datetime from a POSIX timestamp."""
  1497. import warnings
  1498. warnings.warn("datetime.datetime.utcfromtimestamp() is deprecated and scheduled "
  1499. "for removal in a future version. Use timezone-aware "
  1500. "objects to represent datetimes in UTC: "
  1501. "datetime.datetime.fromtimestamp(t, datetime.UTC).",
  1502. DeprecationWarning,
  1503. stacklevel=2)
  1504. return cls._fromtimestamp(t, True, None)
  1505. @classmethod
  1506. def now(cls, tz=None):
  1507. "Construct a datetime from time.time() and optional time zone info."
  1508. t = _time.time()
  1509. return cls.fromtimestamp(t, tz)
  1510. @classmethod
  1511. def utcnow(cls):
  1512. "Construct a UTC datetime from time.time()."
  1513. import warnings
  1514. warnings.warn("datetime.datetime.utcnow() is deprecated and scheduled for "
  1515. "removal in a future version. Use timezone-aware "
  1516. "objects to represent datetimes in UTC: "
  1517. "datetime.datetime.now(datetime.UTC).",
  1518. DeprecationWarning,
  1519. stacklevel=2)
  1520. t = _time.time()
  1521. return cls._fromtimestamp(t, True, None)
  1522. @classmethod
  1523. def combine(cls, date, time, tzinfo=True):
  1524. "Construct a datetime from a given date and a given time."
  1525. if not isinstance(date, _date_class):
  1526. raise TypeError("date argument must be a date instance")
  1527. if not isinstance(time, _time_class):
  1528. raise TypeError("time argument must be a time instance")
  1529. if tzinfo is True:
  1530. tzinfo = time.tzinfo
  1531. return cls(date.year, date.month, date.day,
  1532. time.hour, time.minute, time.second, time.microsecond,
  1533. tzinfo, fold=time.fold)
  1534. @classmethod
  1535. def fromisoformat(cls, date_string):
  1536. """Construct a datetime from a string in one of the ISO 8601 formats."""
  1537. if not isinstance(date_string, str):
  1538. raise TypeError('fromisoformat: argument must be str')
  1539. if len(date_string) < 7:
  1540. raise ValueError(f'Invalid isoformat string: {date_string!r}')
  1541. # Split this at the separator
  1542. try:
  1543. separator_location = _find_isoformat_datetime_separator(date_string)
  1544. dstr = date_string[0:separator_location]
  1545. tstr = date_string[(separator_location+1):]
  1546. date_components = _parse_isoformat_date(dstr)
  1547. except ValueError:
  1548. raise ValueError(
  1549. f'Invalid isoformat string: {date_string!r}') from None
  1550. if tstr:
  1551. try:
  1552. time_components = _parse_isoformat_time(tstr)
  1553. except ValueError:
  1554. raise ValueError(
  1555. f'Invalid isoformat string: {date_string!r}') from None
  1556. else:
  1557. time_components = [0, 0, 0, 0, None]
  1558. return cls(*(date_components + time_components))
  1559. def timetuple(self):
  1560. "Return local time tuple compatible with time.localtime()."
  1561. dst = self.dst()
  1562. if dst is None:
  1563. dst = -1
  1564. elif dst:
  1565. dst = 1
  1566. else:
  1567. dst = 0
  1568. return _build_struct_time(self.year, self.month, self.day,
  1569. self.hour, self.minute, self.second,
  1570. dst)
  1571. def _mktime(self):
  1572. """Return integer POSIX timestamp."""
  1573. epoch = datetime(1970, 1, 1)
  1574. max_fold_seconds = 24 * 3600
  1575. t = (self - epoch) // timedelta(0, 1)
  1576. def local(u):
  1577. y, m, d, hh, mm, ss = _time.localtime(u)[:6]
  1578. return (datetime(y, m, d, hh, mm, ss) - epoch) // timedelta(0, 1)
  1579. # Our goal is to solve t = local(u) for u.
  1580. a = local(t) - t
  1581. u1 = t - a
  1582. t1 = local(u1)
  1583. if t1 == t:
  1584. # We found one solution, but it may not be the one we need.
  1585. # Look for an earlier solution (if `fold` is 0), or a
  1586. # later one (if `fold` is 1).
  1587. u2 = u1 + (-max_fold_seconds, max_fold_seconds)[self.fold]
  1588. b = local(u2) - u2
  1589. if a == b:
  1590. return u1
  1591. else:
  1592. b = t1 - u1
  1593. assert a != b
  1594. u2 = t - b
  1595. t2 = local(u2)
  1596. if t2 == t:
  1597. return u2
  1598. if t1 == t:
  1599. return u1
  1600. # We have found both offsets a and b, but neither t - a nor t - b is
  1601. # a solution. This means t is in the gap.
  1602. return (max, min)[self.fold](u1, u2)
  1603. def timestamp(self):
  1604. "Return POSIX timestamp as float"
  1605. if self._tzinfo is None:
  1606. s = self._mktime()
  1607. return s + self.microsecond / 1e6
  1608. else:
  1609. return (self - _EPOCH).total_seconds()
  1610. def utctimetuple(self):
  1611. "Return UTC time tuple compatible with time.gmtime()."
  1612. offset = self.utcoffset()
  1613. if offset:
  1614. self -= offset
  1615. y, m, d = self.year, self.month, self.day
  1616. hh, mm, ss = self.hour, self.minute, self.second
  1617. return _build_struct_time(y, m, d, hh, mm, ss, 0)
  1618. def date(self):
  1619. "Return the date part."
  1620. return date(self._year, self._month, self._day)
  1621. def time(self):
  1622. "Return the time part, with tzinfo None."
  1623. return time(self.hour, self.minute, self.second, self.microsecond, fold=self.fold)
  1624. def timetz(self):
  1625. "Return the time part, with same tzinfo."
  1626. return time(self.hour, self.minute, self.second, self.microsecond,
  1627. self._tzinfo, fold=self.fold)
  1628. def replace(self, year=None, month=None, day=None, hour=None,
  1629. minute=None, second=None, microsecond=None, tzinfo=True,
  1630. *, fold=None):
  1631. """Return a new datetime with new values for the specified fields."""
  1632. if year is None:
  1633. year = self.year
  1634. if month is None:
  1635. month = self.month
  1636. if day is None:
  1637. day = self.day
  1638. if hour is None:
  1639. hour = self.hour
  1640. if minute is None:
  1641. minute = self.minute
  1642. if second is None:
  1643. second = self.second
  1644. if microsecond is None:
  1645. microsecond = self.microsecond
  1646. if tzinfo is True:
  1647. tzinfo = self.tzinfo
  1648. if fold is None:
  1649. fold = self.fold
  1650. return type(self)(year, month, day, hour, minute, second,
  1651. microsecond, tzinfo, fold=fold)
  1652. def _local_timezone(self):
  1653. if self.tzinfo is None:
  1654. ts = self._mktime()
  1655. # Detect gap
  1656. ts2 = self.replace(fold=1-self.fold)._mktime()
  1657. if ts2 != ts: # This happens in a gap or a fold
  1658. if (ts2 > ts) == self.fold:
  1659. ts = ts2
  1660. else:
  1661. ts = (self - _EPOCH) // timedelta(seconds=1)
  1662. localtm = _time.localtime(ts)
  1663. local = datetime(*localtm[:6])
  1664. # Extract TZ data
  1665. gmtoff = localtm.tm_gmtoff
  1666. zone = localtm.tm_zone
  1667. return timezone(timedelta(seconds=gmtoff), zone)
  1668. def astimezone(self, tz=None):
  1669. if tz is None:
  1670. tz = self._local_timezone()
  1671. elif not isinstance(tz, tzinfo):
  1672. raise TypeError("tz argument must be an instance of tzinfo")
  1673. mytz = self.tzinfo
  1674. if mytz is None:
  1675. mytz = self._local_timezone()
  1676. myoffset = mytz.utcoffset(self)
  1677. else:
  1678. myoffset = mytz.utcoffset(self)
  1679. if myoffset is None:
  1680. mytz = self.replace(tzinfo=None)._local_timezone()
  1681. myoffset = mytz.utcoffset(self)
  1682. if tz is mytz:
  1683. return self
  1684. # Convert self to UTC, and attach the new time zone object.
  1685. utc = (self - myoffset).replace(tzinfo=tz)
  1686. # Convert from UTC to tz's local time.
  1687. return tz.fromutc(utc)
  1688. # Ways to produce a string.
  1689. def ctime(self):
  1690. "Return ctime() style string."
  1691. weekday = self.toordinal() % 7 or 7
  1692. return "%s %s %2d %02d:%02d:%02d %04d" % (
  1693. _DAYNAMES[weekday],
  1694. _MONTHNAMES[self._month],
  1695. self._day,
  1696. self._hour, self._minute, self._second,
  1697. self._year)
  1698. def isoformat(self, sep='T', timespec='auto'):
  1699. """Return the time formatted according to ISO.
  1700. The full format looks like 'YYYY-MM-DD HH:MM:SS.mmmmmm'.
  1701. By default, the fractional part is omitted if self.microsecond == 0.
  1702. If self.tzinfo is not None, the UTC offset is also attached, giving
  1703. giving a full format of 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM'.
  1704. Optional argument sep specifies the separator between date and
  1705. time, default 'T'.
  1706. The optional argument timespec specifies the number of additional
  1707. terms of the time to include. Valid options are 'auto', 'hours',
  1708. 'minutes', 'seconds', 'milliseconds' and 'microseconds'.
  1709. """
  1710. s = ("%04d-%02d-%02d%c" % (self._year, self._month, self._day, sep) +
  1711. _format_time(self._hour, self._minute, self._second,
  1712. self._microsecond, timespec))
  1713. off = self.utcoffset()
  1714. tz = _format_offset(off)
  1715. if tz:
  1716. s += tz
  1717. return s
  1718. def __repr__(self):
  1719. """Convert to formal string, for repr()."""
  1720. L = [self._year, self._month, self._day, # These are never zero
  1721. self._hour, self._minute, self._second, self._microsecond]
  1722. if L[-1] == 0:
  1723. del L[-1]
  1724. if L[-1] == 0:
  1725. del L[-1]
  1726. s = "%s.%s(%s)" % (_get_class_module(self),
  1727. self.__class__.__qualname__,
  1728. ", ".join(map(str, L)))
  1729. if self._tzinfo is not None:
  1730. assert s[-1:] == ")"
  1731. s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")"
  1732. if self._fold:
  1733. assert s[-1:] == ")"
  1734. s = s[:-1] + ", fold=1)"
  1735. return s
  1736. def __str__(self):
  1737. "Convert to string, for str()."
  1738. return self.isoformat(sep=' ')
  1739. @classmethod
  1740. def strptime(cls, date_string, format):
  1741. 'string, format -> new datetime parsed from a string (like time.strptime()).'
  1742. import _strptime
  1743. return _strptime._strptime_datetime(cls, date_string, format)
  1744. def utcoffset(self):
  1745. """Return the timezone offset as timedelta positive east of UTC (negative west of
  1746. UTC)."""
  1747. if self._tzinfo is None:
  1748. return None
  1749. offset = self._tzinfo.utcoffset(self)
  1750. _check_utc_offset("utcoffset", offset)
  1751. return offset
  1752. def tzname(self):
  1753. """Return the timezone name.
  1754. Note that the name is 100% informational -- there's no requirement that
  1755. it mean anything in particular. For example, "GMT", "UTC", "-500",
  1756. "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
  1757. """
  1758. if self._tzinfo is None:
  1759. return None
  1760. name = self._tzinfo.tzname(self)
  1761. _check_tzname(name)
  1762. return name
  1763. def dst(self):
  1764. """Return 0 if DST is not in effect, or the DST offset (as timedelta
  1765. positive eastward) if DST is in effect.
  1766. This is purely informational; the DST offset has already been added to
  1767. the UTC offset returned by utcoffset() if applicable, so there's no
  1768. need to consult dst() unless you're interested in displaying the DST
  1769. info.
  1770. """
  1771. if self._tzinfo is None:
  1772. return None
  1773. offset = self._tzinfo.dst(self)
  1774. _check_utc_offset("dst", offset)
  1775. return offset
  1776. # Comparisons of datetime objects with other.
  1777. def __eq__(self, other):
  1778. if isinstance(other, datetime):
  1779. return self._cmp(other, allow_mixed=True) == 0
  1780. elif not isinstance(other, date):
  1781. return NotImplemented
  1782. else:
  1783. return False
  1784. def __le__(self, other):
  1785. if isinstance(other, datetime):
  1786. return self._cmp(other) <= 0
  1787. elif not isinstance(other, date):
  1788. return NotImplemented
  1789. else:
  1790. _cmperror(self, other)
  1791. def __lt__(self, other):
  1792. if isinstance(other, datetime):
  1793. return self._cmp(other) < 0
  1794. elif not isinstance(other, date):
  1795. return NotImplemented
  1796. else:
  1797. _cmperror(self, other)
  1798. def __ge__(self, other):
  1799. if isinstance(other, datetime):
  1800. return self._cmp(other) >= 0
  1801. elif not isinstance(other, date):
  1802. return NotImplemented
  1803. else:
  1804. _cmperror(self, other)
  1805. def __gt__(self, other):
  1806. if isinstance(other, datetime):
  1807. return self._cmp(other) > 0
  1808. elif not isinstance(other, date):
  1809. return NotImplemented
  1810. else:
  1811. _cmperror(self, other)
  1812. def _cmp(self, other, allow_mixed=False):
  1813. assert isinstance(other, datetime)
  1814. mytz = self._tzinfo
  1815. ottz = other._tzinfo
  1816. myoff = otoff = None
  1817. if mytz is ottz:
  1818. base_compare = True
  1819. else:
  1820. myoff = self.utcoffset()
  1821. otoff = other.utcoffset()
  1822. # Assume that allow_mixed means that we are called from __eq__
  1823. if allow_mixed:
  1824. if myoff != self.replace(fold=not self.fold).utcoffset():
  1825. return 2
  1826. if otoff != other.replace(fold=not other.fold).utcoffset():
  1827. return 2
  1828. base_compare = myoff == otoff
  1829. if base_compare:
  1830. return _cmp((self._year, self._month, self._day,
  1831. self._hour, self._minute, self._second,
  1832. self._microsecond),
  1833. (other._year, other._month, other._day,
  1834. other._hour, other._minute, other._second,
  1835. other._microsecond))
  1836. if myoff is None or otoff is None:
  1837. if allow_mixed:
  1838. return 2 # arbitrary non-zero value
  1839. else:
  1840. raise TypeError("cannot compare naive and aware datetimes")
  1841. # XXX What follows could be done more efficiently...
  1842. diff = self - other # this will take offsets into account
  1843. if diff.days < 0:
  1844. return -1
  1845. return diff and 1 or 0
  1846. def __add__(self, other):
  1847. "Add a datetime and a timedelta."
  1848. if not isinstance(other, timedelta):
  1849. return NotImplemented
  1850. delta = timedelta(self.toordinal(),
  1851. hours=self._hour,
  1852. minutes=self._minute,
  1853. seconds=self._second,
  1854. microseconds=self._microsecond)
  1855. delta += other
  1856. hour, rem = divmod(delta.seconds, 3600)
  1857. minute, second = divmod(rem, 60)
  1858. if 0 < delta.days <= _MAXORDINAL:
  1859. return type(self).combine(date.fromordinal(delta.days),
  1860. time(hour, minute, second,
  1861. delta.microseconds,
  1862. tzinfo=self._tzinfo))
  1863. raise OverflowError("result out of range")
  1864. __radd__ = __add__
  1865. def __sub__(self, other):
  1866. "Subtract two datetimes, or a datetime and a timedelta."
  1867. if not isinstance(other, datetime):
  1868. if isinstance(other, timedelta):
  1869. return self + -other
  1870. return NotImplemented
  1871. days1 = self.toordinal()
  1872. days2 = other.toordinal()
  1873. secs1 = self._second + self._minute * 60 + self._hour * 3600
  1874. secs2 = other._second + other._minute * 60 + other._hour * 3600
  1875. base = timedelta(days1 - days2,
  1876. secs1 - secs2,
  1877. self._microsecond - other._microsecond)
  1878. if self._tzinfo is other._tzinfo:
  1879. return base
  1880. myoff = self.utcoffset()
  1881. otoff = other.utcoffset()
  1882. if myoff == otoff:
  1883. return base
  1884. if myoff is None or otoff is None:
  1885. raise TypeError("cannot mix naive and timezone-aware time")
  1886. return base + otoff - myoff
  1887. def __hash__(self):
  1888. if self._hashcode == -1:
  1889. if self.fold:
  1890. t = self.replace(fold=0)
  1891. else:
  1892. t = self
  1893. tzoff = t.utcoffset()
  1894. if tzoff is None:
  1895. self._hashcode = hash(t._getstate()[0])
  1896. else:
  1897. days = _ymd2ord(self.year, self.month, self.day)
  1898. seconds = self.hour * 3600 + self.minute * 60 + self.second
  1899. self._hashcode = hash(timedelta(days, seconds, self.microsecond) - tzoff)
  1900. return self._hashcode
  1901. # Pickle support.
  1902. def _getstate(self, protocol=3):
  1903. yhi, ylo = divmod(self._year, 256)
  1904. us2, us3 = divmod(self._microsecond, 256)
  1905. us1, us2 = divmod(us2, 256)
  1906. m = self._month
  1907. if self._fold and protocol > 3:
  1908. m += 128
  1909. basestate = bytes([yhi, ylo, m, self._day,
  1910. self._hour, self._minute, self._second,
  1911. us1, us2, us3])
  1912. if self._tzinfo is None:
  1913. return (basestate,)
  1914. else:
  1915. return (basestate, self._tzinfo)
  1916. def __setstate(self, string, tzinfo):
  1917. if tzinfo is not None and not isinstance(tzinfo, _tzinfo_class):
  1918. raise TypeError("bad tzinfo state arg")
  1919. (yhi, ylo, m, self._day, self._hour,
  1920. self._minute, self._second, us1, us2, us3) = string
  1921. if m > 127:
  1922. self._fold = 1
  1923. self._month = m - 128
  1924. else:
  1925. self._fold = 0
  1926. self._month = m
  1927. self._year = yhi * 256 + ylo
  1928. self._microsecond = (((us1 << 8) | us2) << 8) | us3
  1929. self._tzinfo = tzinfo
  1930. def __reduce_ex__(self, protocol):
  1931. return (self.__class__, self._getstate(protocol))
  1932. def __reduce__(self):
  1933. return self.__reduce_ex__(2)
  1934. datetime.min = datetime(1, 1, 1)
  1935. datetime.max = datetime(9999, 12, 31, 23, 59, 59, 999999)
  1936. datetime.resolution = timedelta(microseconds=1)
  1937. def _isoweek1monday(year):
  1938. # Helper to calculate the day number of the Monday starting week 1
  1939. # XXX This could be done more efficiently
  1940. THURSDAY = 3
  1941. firstday = _ymd2ord(year, 1, 1)
  1942. firstweekday = (firstday + 6) % 7 # See weekday() above
  1943. week1monday = firstday - firstweekday
  1944. if firstweekday > THURSDAY:
  1945. week1monday += 7
  1946. return week1monday
  1947. class timezone(tzinfo):
  1948. __slots__ = '_offset', '_name'
  1949. # Sentinel value to disallow None
  1950. _Omitted = object()
  1951. def __new__(cls, offset, name=_Omitted):
  1952. if not isinstance(offset, timedelta):
  1953. raise TypeError("offset must be a timedelta")
  1954. if name is cls._Omitted:
  1955. if not offset:
  1956. return cls.utc
  1957. name = None
  1958. elif not isinstance(name, str):
  1959. raise TypeError("name must be a string")
  1960. if not cls._minoffset <= offset <= cls._maxoffset:
  1961. raise ValueError("offset must be a timedelta "
  1962. "strictly between -timedelta(hours=24) and "
  1963. "timedelta(hours=24).")
  1964. return cls._create(offset, name)
  1965. @classmethod
  1966. def _create(cls, offset, name=None):
  1967. self = tzinfo.__new__(cls)
  1968. self._offset = offset
  1969. self._name = name
  1970. return self
  1971. def __getinitargs__(self):
  1972. """pickle support"""
  1973. if self._name is None:
  1974. return (self._offset,)
  1975. return (self._offset, self._name)
  1976. def __eq__(self, other):
  1977. if isinstance(other, timezone):
  1978. return self._offset == other._offset
  1979. return NotImplemented
  1980. def __hash__(self):
  1981. return hash(self._offset)
  1982. def __repr__(self):
  1983. """Convert to formal string, for repr().
  1984. >>> tz = timezone.utc
  1985. >>> repr(tz)
  1986. 'datetime.timezone.utc'
  1987. >>> tz = timezone(timedelta(hours=-5), 'EST')
  1988. >>> repr(tz)
  1989. "datetime.timezone(datetime.timedelta(-1, 68400), 'EST')"
  1990. """
  1991. if self is self.utc:
  1992. return 'datetime.timezone.utc'
  1993. if self._name is None:
  1994. return "%s.%s(%r)" % (_get_class_module(self),
  1995. self.__class__.__qualname__,
  1996. self._offset)
  1997. return "%s.%s(%r, %r)" % (_get_class_module(self),
  1998. self.__class__.__qualname__,
  1999. self._offset, self._name)
  2000. def __str__(self):
  2001. return self.tzname(None)
  2002. def utcoffset(self, dt):
  2003. if isinstance(dt, datetime) or dt is None:
  2004. return self._offset
  2005. raise TypeError("utcoffset() argument must be a datetime instance"
  2006. " or None")
  2007. def tzname(self, dt):
  2008. if isinstance(dt, datetime) or dt is None:
  2009. if self._name is None:
  2010. return self._name_from_offset(self._offset)
  2011. return self._name
  2012. raise TypeError("tzname() argument must be a datetime instance"
  2013. " or None")
  2014. def dst(self, dt):
  2015. if isinstance(dt, datetime) or dt is None:
  2016. return None
  2017. raise TypeError("dst() argument must be a datetime instance"
  2018. " or None")
  2019. def fromutc(self, dt):
  2020. if isinstance(dt, datetime):
  2021. if dt.tzinfo is not self:
  2022. raise ValueError("fromutc: dt.tzinfo "
  2023. "is not self")
  2024. return dt + self._offset
  2025. raise TypeError("fromutc() argument must be a datetime instance"
  2026. " or None")
  2027. _maxoffset = timedelta(hours=24, microseconds=-1)
  2028. _minoffset = -_maxoffset
  2029. @staticmethod
  2030. def _name_from_offset(delta):
  2031. if not delta:
  2032. return 'UTC'
  2033. if delta < timedelta(0):
  2034. sign = '-'
  2035. delta = -delta
  2036. else:
  2037. sign = '+'
  2038. hours, rest = divmod(delta, timedelta(hours=1))
  2039. minutes, rest = divmod(rest, timedelta(minutes=1))
  2040. seconds = rest.seconds
  2041. microseconds = rest.microseconds
  2042. if microseconds:
  2043. return (f'UTC{sign}{hours:02d}:{minutes:02d}:{seconds:02d}'
  2044. f'.{microseconds:06d}')
  2045. if seconds:
  2046. return f'UTC{sign}{hours:02d}:{minutes:02d}:{seconds:02d}'
  2047. return f'UTC{sign}{hours:02d}:{minutes:02d}'
  2048. UTC = timezone.utc = timezone._create(timedelta(0))
  2049. # bpo-37642: These attributes are rounded to the nearest minute for backwards
  2050. # compatibility, even though the constructor will accept a wider range of
  2051. # values. This may change in the future.
  2052. timezone.min = timezone._create(-timedelta(hours=23, minutes=59))
  2053. timezone.max = timezone._create(timedelta(hours=23, minutes=59))
  2054. _EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
  2055. # Some time zone algebra. For a datetime x, let
  2056. # x.n = x stripped of its timezone -- its naive time.
  2057. # x.o = x.utcoffset(), and assuming that doesn't raise an exception or
  2058. # return None
  2059. # x.d = x.dst(), and assuming that doesn't raise an exception or
  2060. # return None
  2061. # x.s = x's standard offset, x.o - x.d
  2062. #
  2063. # Now some derived rules, where k is a duration (timedelta).
  2064. #
  2065. # 1. x.o = x.s + x.d
  2066. # This follows from the definition of x.s.
  2067. #
  2068. # 2. If x and y have the same tzinfo member, x.s = y.s.
  2069. # This is actually a requirement, an assumption we need to make about
  2070. # sane tzinfo classes.
  2071. #
  2072. # 3. The naive UTC time corresponding to x is x.n - x.o.
  2073. # This is again a requirement for a sane tzinfo class.
  2074. #
  2075. # 4. (x+k).s = x.s
  2076. # This follows from #2, and that datetime.timetz+timedelta preserves tzinfo.
  2077. #
  2078. # 5. (x+k).n = x.n + k
  2079. # Again follows from how arithmetic is defined.
  2080. #
  2081. # Now we can explain tz.fromutc(x). Let's assume it's an interesting case
  2082. # (meaning that the various tzinfo methods exist, and don't blow up or return
  2083. # None when called).
  2084. #
  2085. # The function wants to return a datetime y with timezone tz, equivalent to x.
  2086. # x is already in UTC.
  2087. #
  2088. # By #3, we want
  2089. #
  2090. # y.n - y.o = x.n [1]
  2091. #
  2092. # The algorithm starts by attaching tz to x.n, and calling that y. So
  2093. # x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
  2094. # becomes true; in effect, we want to solve [2] for k:
  2095. #
  2096. # (y+k).n - (y+k).o = x.n [2]
  2097. #
  2098. # By #1, this is the same as
  2099. #
  2100. # (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
  2101. #
  2102. # By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
  2103. # Substituting that into [3],
  2104. #
  2105. # x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
  2106. # k - (y+k).s - (y+k).d = 0; rearranging,
  2107. # k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
  2108. # k = y.s - (y+k).d
  2109. #
  2110. # On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
  2111. # approximate k by ignoring the (y+k).d term at first. Note that k can't be
  2112. # very large, since all offset-returning methods return a duration of magnitude
  2113. # less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
  2114. # be 0, so ignoring it has no consequence then.
  2115. #
  2116. # In any case, the new value is
  2117. #
  2118. # z = y + y.s [4]
  2119. #
  2120. # It's helpful to step back at look at [4] from a higher level: it's simply
  2121. # mapping from UTC to tz's standard time.
  2122. #
  2123. # At this point, if
  2124. #
  2125. # z.n - z.o = x.n [5]
  2126. #
  2127. # we have an equivalent time, and are almost done. The insecurity here is
  2128. # at the start of daylight time. Picture US Eastern for concreteness. The wall
  2129. # time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
  2130. # sense then. The docs ask that an Eastern tzinfo class consider such a time to
  2131. # be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
  2132. # on the day DST starts. We want to return the 1:MM EST spelling because that's
  2133. # the only spelling that makes sense on the local wall clock.
  2134. #
  2135. # In fact, if [5] holds at this point, we do have the standard-time spelling,
  2136. # but that takes a bit of proof. We first prove a stronger result. What's the
  2137. # difference between the LHS and RHS of [5]? Let
  2138. #
  2139. # diff = x.n - (z.n - z.o) [6]
  2140. #
  2141. # Now
  2142. # z.n = by [4]
  2143. # (y + y.s).n = by #5
  2144. # y.n + y.s = since y.n = x.n
  2145. # x.n + y.s = since z and y are have the same tzinfo member,
  2146. # y.s = z.s by #2
  2147. # x.n + z.s
  2148. #
  2149. # Plugging that back into [6] gives
  2150. #
  2151. # diff =
  2152. # x.n - ((x.n + z.s) - z.o) = expanding
  2153. # x.n - x.n - z.s + z.o = cancelling
  2154. # - z.s + z.o = by #2
  2155. # z.d
  2156. #
  2157. # So diff = z.d.
  2158. #
  2159. # If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
  2160. # spelling we wanted in the endcase described above. We're done. Contrarily,
  2161. # if z.d = 0, then we have a UTC equivalent, and are also done.
  2162. #
  2163. # If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
  2164. # add to z (in effect, z is in tz's standard time, and we need to shift the
  2165. # local clock into tz's daylight time).
  2166. #
  2167. # Let
  2168. #
  2169. # z' = z + z.d = z + diff [7]
  2170. #
  2171. # and we can again ask whether
  2172. #
  2173. # z'.n - z'.o = x.n [8]
  2174. #
  2175. # If so, we're done. If not, the tzinfo class is insane, according to the
  2176. # assumptions we've made. This also requires a bit of proof. As before, let's
  2177. # compute the difference between the LHS and RHS of [8] (and skipping some of
  2178. # the justifications for the kinds of substitutions we've done several times
  2179. # already):
  2180. #
  2181. # diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
  2182. # x.n - (z.n + diff - z'.o) = replacing diff via [6]
  2183. # x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
  2184. # x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
  2185. # - z.n + z.n - z.o + z'.o = cancel z.n
  2186. # - z.o + z'.o = #1 twice
  2187. # -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
  2188. # z'.d - z.d
  2189. #
  2190. # So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
  2191. # we've found the UTC-equivalent so are done. In fact, we stop with [7] and
  2192. # return z', not bothering to compute z'.d.
  2193. #
  2194. # How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
  2195. # a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
  2196. # would have to change the result dst() returns: we start in DST, and moving
  2197. # a little further into it takes us out of DST.
  2198. #
  2199. # There isn't a sane case where this can happen. The closest it gets is at
  2200. # the end of DST, where there's an hour in UTC with no spelling in a hybrid
  2201. # tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
  2202. # that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
  2203. # UTC) because the docs insist on that, but 0:MM is taken as being in daylight
  2204. # time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
  2205. # clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
  2206. # standard time. Since that's what the local clock *does*, we want to map both
  2207. # UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
  2208. # in local time, but so it goes -- it's the way the local clock works.
  2209. #
  2210. # When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
  2211. # so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
  2212. # z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
  2213. # (correctly) concludes that z' is not UTC-equivalent to x.
  2214. #
  2215. # Because we know z.d said z was in daylight time (else [5] would have held and
  2216. # we would have stopped then), and we know z.d != z'.d (else [8] would have held
  2217. # and we have stopped then), and there are only 2 possible values dst() can
  2218. # return in Eastern, it follows that z'.d must be 0 (which it is in the example,
  2219. # but the reasoning doesn't depend on the example -- it depends on there being
  2220. # two possible dst() outcomes, one zero and the other non-zero). Therefore
  2221. # z' must be in standard time, and is the spelling we want in this case.
  2222. #
  2223. # Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
  2224. # concerned (because it takes z' as being in standard time rather than the
  2225. # daylight time we intend here), but returning it gives the real-life "local
  2226. # clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
  2227. # tz.
  2228. #
  2229. # When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
  2230. # the 1:MM standard time spelling we want.
  2231. #
  2232. # So how can this break? One of the assumptions must be violated. Two
  2233. # possibilities:
  2234. #
  2235. # 1) [2] effectively says that y.s is invariant across all y belong to a given
  2236. # time zone. This isn't true if, for political reasons or continental drift,
  2237. # a region decides to change its base offset from UTC.
  2238. #
  2239. # 2) There may be versions of "double daylight" time where the tail end of
  2240. # the analysis gives up a step too early. I haven't thought about that
  2241. # enough to say.
  2242. #
  2243. # In any case, it's clear that the default fromutc() is strong enough to handle
  2244. # "almost all" time zones: so long as the standard offset is invariant, it
  2245. # doesn't matter if daylight time transition points change from year to year, or
  2246. # if daylight time is skipped in some years; it doesn't matter how large or
  2247. # small dst() may get within its bounds; and it doesn't even matter if some
  2248. # perverse time zone returns a negative dst()). So a breaking case must be
  2249. # pretty bizarre, and a tzinfo subclass can override fromutc() if it is.