_pydatetime.py 90 KB

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