logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

datetime.py (88059B)


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