acclivity

pyUnixtime2UTC

Jan 28th, 2021 (edited)
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.44 KB | None | 0 0
  1. # Convert Unix Time to current UTC data and time, without using Datetime module
  2. # Mike Kerry - 28-Jan-2021 - [email protected]
  3. # **BUG FIXED 28-Jan 14:00 UTC !!
  4.  
  5. # Unix Time is the number of seconds that have elapsed since 00:00:00 UTC on 01-Jan-1970
  6. # Because year 2000 is a leap year (unlike 1900 or 2100 etc.) this code will work from 1970 to 2099
  7. # (or until some time in year 2038 when 32-bit Unix timestamps overflow - if we are not all on 64-bit by then!)
  8.  
  9. import time         # Unix Time is available from the "time" module
  10.  
  11.  
  12. def n2(n):
  13.     # A little function to format an integer 0 to 99 into a 2-character string with leading zero where needed
  14.     return str(n + 100)[1:]
  15.  
  16.  
  17. secs_per_day = 86400                                # A useful constant
  18. unix_now = int(time.time())                         # Unix time is seconds since 1-Jan-1970
  19. days_per_4years = 365 * 4 + 1                       # a span of 4 years has 1461 days (365 * 3 + 366)
  20. secs_per_4years = days_per_4years * secs_per_day
  21. count_of_4years = unix_now // secs_per_4years       # compute number of 4-year spans that have elapsed since 1970
  22.  
  23. secs_into_4years = unix_now - count_of_4years * secs_per_4years
  24. days_into_4years = secs_into_4years // secs_per_day
  25.  
  26. year = int(1970 + count_of_4years * 4)
  27.  
  28. days_into_year = 1 + days_into_4years       # Plus 1 because the base date is 1st Jan, not day zero
  29. if days_into_year > 365:
  30.     days_into_year -= 365       # count a non-leap year e.g. 1970
  31.     year += 1
  32. if days_into_year > 365:
  33.     days_into_year -= 365       # count a non-leap year e.g. 1971
  34.     year += 1
  35. if days_into_year > 366:
  36.     days_into_year -= 366       # count a leap year e.g. 1972
  37.     year += 1
  38.  
  39. feb_days = 28
  40. if not year & 3:          # is year divisible by 4? (faster and neater than year % 4)
  41.     feb_days = 29         # year is a leap year
  42. days_by_month = [0, 31, feb_days, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]     # table of days by month (Jan is month 1)
  43. day = days_into_year
  44. # Convert days_into_year into month and day
  45. for mon, num in enumerate(days_by_month):
  46.     if day <= num:              # BUG FIX !!
  47.         break
  48.     day -= num
  49.  
  50. # Compute time of day in hours, minutes, and seconds
  51. secs_into_day = unix_now % secs_per_day
  52. hours = secs_into_day // 3600
  53. mins = (secs_into_day // 60) % 60
  54. secs = (secs_into_day - (hours * 3600) - (mins * 60))
  55.  
  56. print(str(year) + "-" + n2(mon) + "-" + n2(day) + " " + n2(hours) + ":" + n2(mins) + ":" + n2(secs))
  57.  
Add Comment
Please, Sign In to add comment