Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Convert Unix Time to current UTC data and time, without using Datetime module
- # Mike Kerry - 28-Jan-2021 - [email protected]
- # **BUG FIXED 28-Jan 14:00 UTC !!
- # Unix Time is the number of seconds that have elapsed since 00:00:00 UTC on 01-Jan-1970
- # Because year 2000 is a leap year (unlike 1900 or 2100 etc.) this code will work from 1970 to 2099
- # (or until some time in year 2038 when 32-bit Unix timestamps overflow - if we are not all on 64-bit by then!)
- import time # Unix Time is available from the "time" module
- def n2(n):
- # A little function to format an integer 0 to 99 into a 2-character string with leading zero where needed
- return str(n + 100)[1:]
- secs_per_day = 86400 # A useful constant
- unix_now = int(time.time()) # Unix time is seconds since 1-Jan-1970
- days_per_4years = 365 * 4 + 1 # a span of 4 years has 1461 days (365 * 3 + 366)
- secs_per_4years = days_per_4years * secs_per_day
- count_of_4years = unix_now // secs_per_4years # compute number of 4-year spans that have elapsed since 1970
- secs_into_4years = unix_now - count_of_4years * secs_per_4years
- days_into_4years = secs_into_4years // secs_per_day
- year = int(1970 + count_of_4years * 4)
- days_into_year = 1 + days_into_4years # Plus 1 because the base date is 1st Jan, not day zero
- if days_into_year > 365:
- days_into_year -= 365 # count a non-leap year e.g. 1970
- year += 1
- if days_into_year > 365:
- days_into_year -= 365 # count a non-leap year e.g. 1971
- year += 1
- if days_into_year > 366:
- days_into_year -= 366 # count a leap year e.g. 1972
- year += 1
- feb_days = 28
- if not year & 3: # is year divisible by 4? (faster and neater than year % 4)
- feb_days = 29 # year is a leap year
- 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)
- day = days_into_year
- # Convert days_into_year into month and day
- for mon, num in enumerate(days_by_month):
- if day <= num: # BUG FIX !!
- break
- day -= num
- # Compute time of day in hours, minutes, and seconds
- secs_into_day = unix_now % secs_per_day
- hours = secs_into_day // 3600
- mins = (secs_into_day // 60) % 60
- secs = (secs_into_day - (hours * 3600) - (mins * 60))
- print(str(year) + "-" + n2(mon) + "-" + n2(day) + " " + n2(hours) + ":" + n2(mins) + ":" + n2(secs))
Add Comment
Please, Sign In to add comment