Advertisement
Guest User

Untitled

a guest
Jan 3rd, 2022
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.60 KB | None | 0 0
  1. SECONDS_PER_UNIX_DAY = 24 * 60 * 60
  2. DAYS_PER_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  3.  
  4.  
  5. def is_leap(year):
  6.     return ((year % 4) == 0 and not (year % 100) == 0) or (year % 400) == 0
  7.  
  8.  
  9. def in_month(epoch, month):
  10.     assert epoch > 0, "Unix time is only defined after 1.1.1970, 00:00:00 UTC"
  11.     assert 1 <= month < 12, "Invalid month"
  12.     year = 1970
  13.     epoch_of_year = 0
  14.  
  15.     while True:
  16.         cur_year = (366 if is_leap(year) else 365) * SECONDS_PER_UNIX_DAY
  17.         if cur_year + epoch_of_year > epoch:
  18.             break
  19.         year += 1
  20.         epoch_of_year += cur_year
  21.  
  22.     days = epoch - epoch_of_year
  23.     _mos = list()
  24.     _mos[:] = DAYS_PER_MONTH[:]
  25.     if is_leap(year):
  26.         _mos[1] += 1
  27.     month_start = sum(_mos[:month - 1]) * SECONDS_PER_UNIX_DAY
  28.     month_end = sum(_mos[:month]) * SECONDS_PER_UNIX_DAY
  29.     return month_start <= days < month_end
  30.  
  31.  
  32. def which_month(epoch):
  33.     for month_no in range(1, 13):
  34.         if in_month(epoch, month_no):
  35.             return month_no
  36.     raise Exception("This should never happen")
  37.  
  38.  
  39. def in_may(epoch):
  40.     return in_month(epoch, 5)
  41.  
  42.  
  43. for ts, may, mo, _ in (
  44.         (1178209938,  True, 5, "# Thu May 03 2007 16:32:18 GMT+0000  # květen nepřestupný"),
  45.         ( 957371538,  True, 5, "# Wed May 03 2000 16:32:18 GMT+0000  # květen přestupný"),
  46.         (1238776338, False, 4, "# Fri Apr 03 2009 16:32:18 GMT+0000  # nekvěten nepřestupný"),
  47.         (1207240338, False, 4, "# Thu Apr 03 2008 16:32:18 GMT+0000  # nekvěten přestupný")
  48. ):
  49.     assert in_may(ts) == may
  50.     assert which_month(ts) == mo
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement