datetime.py 85 KB

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