How to turn a total number of seconds into a date in Python

2 Answers

0 votes
import time
 
def seconds_to_date(seconds):
    struct_time = time.gmtime(seconds)

    day = struct_time.tm_mday
    month = struct_time.tm_mon
    year = struct_time.tm_year
     
    return day, month, year
 
print(seconds_to_date(10_000_000))
 
 
  
'''
run:
  
(26, 4, 1970)
  
'''

 



answered Jan 21 by avibootz
edited Jan 21 by avibootz
0 votes
def seconds_to_date(seconds):
    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)
    days, hours = divmod(hours, 24)
   
    year = 1970
   
    while days > 365:
        if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
            if days > 366:
                days -= 366
                year += 1
            else:
                break
        else:
            days -= 365
            year += 1
   
    days_in_month = [31, 28 + (year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)), 
                     31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
   
    month = 1
    while days >= days_in_month[month - 1]:
        days -= days_in_month[month - 1]
        month += 1
   
    return days + 1, month, year

print(seconds_to_date(10_000_000))


 
'''
run:
 
(26, 4, 1970)
 
'''

 



answered Jan 21 by avibootz

Related questions

...