datetime.py 87 KB

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