datetime.py 86 KB

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