You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

datetime_safe.py 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. # These classes override date and datetime to ensure that strftime('%Y')
  2. # returns four digits (with leading zeros) on years < 1000.
  3. # https://bugs.python.org/issue13305
  4. #
  5. # Based on code submitted to comp.lang.python by Andrew Dalke
  6. #
  7. # >>> datetime_safe.date(10, 8, 2).strftime("%Y/%m/%d was a %A")
  8. # '0010/08/02 was a Monday'
  9. import re
  10. import time as ttime
  11. from datetime import (
  12. date as real_date, datetime as real_datetime, time as real_time,
  13. )
  14. class date(real_date):
  15. def strftime(self, fmt):
  16. return strftime(self, fmt)
  17. class datetime(real_datetime):
  18. def strftime(self, fmt):
  19. return strftime(self, fmt)
  20. @classmethod
  21. def combine(cls, date, time):
  22. return cls(date.year, date.month, date.day,
  23. time.hour, time.minute, time.second,
  24. time.microsecond, time.tzinfo)
  25. def date(self):
  26. return date(self.year, self.month, self.day)
  27. class time(real_time):
  28. pass
  29. def new_date(d):
  30. "Generate a safe date from a datetime.date object."
  31. return date(d.year, d.month, d.day)
  32. def new_datetime(d):
  33. """
  34. Generate a safe datetime from a datetime.date or datetime.datetime object.
  35. """
  36. kw = [d.year, d.month, d.day]
  37. if isinstance(d, real_datetime):
  38. kw.extend([d.hour, d.minute, d.second, d.microsecond, d.tzinfo])
  39. return datetime(*kw)
  40. # This library does not support strftime's "%s" or "%y" format strings.
  41. # Allowed if there's an even number of "%"s because they are escaped.
  42. _illegal_formatting = re.compile(r"((^|[^%])(%%)*%[sy])")
  43. def _findall(text, substr):
  44. # Also finds overlaps
  45. sites = []
  46. i = 0
  47. while True:
  48. i = text.find(substr, i)
  49. if i == -1:
  50. break
  51. sites.append(i)
  52. i += 1
  53. return sites
  54. def strftime(dt, fmt):
  55. if dt.year >= 1000:
  56. return super(type(dt), dt).strftime(fmt)
  57. illegal_formatting = _illegal_formatting.search(fmt)
  58. if illegal_formatting:
  59. raise TypeError("strftime of dates before 1000 does not handle " + illegal_formatting.group(0))
  60. year = dt.year
  61. # For every non-leap year century, advance by
  62. # 6 years to get into the 28-year repeat cycle
  63. delta = 2000 - year
  64. off = 6 * (delta // 100 + delta // 400)
  65. year = year + off
  66. # Move to around the year 2000
  67. year = year + ((2000 - year) // 28) * 28
  68. timetuple = dt.timetuple()
  69. s1 = ttime.strftime(fmt, (year,) + timetuple[1:])
  70. sites1 = _findall(s1, str(year))
  71. s2 = ttime.strftime(fmt, (year + 28,) + timetuple[1:])
  72. sites2 = _findall(s2, str(year + 28))
  73. sites = []
  74. for site in sites1:
  75. if site in sites2:
  76. sites.append(site)
  77. s = s1
  78. syear = "%04d" % (dt.year,)
  79. for site in sites:
  80. s = s[:site] + syear + s[site + 4:]
  81. return s