24

Originally I made this code to convert date into human readable time:

    a = datetime.datetime.strptime(time, "%Y-%m-%d %H:%M:%S.%f")
    b = datetime.datetime.now()
    c = b - a
    days, hours, minutes, seconds = int(c.days), int(c.seconds // 3600), int(c.seconds % 3600 / 60.0), int(c.seconds % 60.0)
    return days, hours, minutes, seconds
    EXAMPLE OUTPUT: 1 days, 4 hours, 24 minutes, 37 seconds

and I'm trying to make it using epoch time, but I have no idea on to make it calculate days hours and etc.

    a = last_epoch #last epoch recorded
    b = time.time() #current epoch time
    c = b - a #returns seconds
    hours = c // 3600 / 24 #the only thing I managed to figure out
Daniel Hyuuga
  • 446
  • 1
  • 5
  • 13
  • 1
    This answer should help you out: [How can I produce a human readable difference when subtracting two UNIX timestamps using Python?](http://stackoverflow.com/questions/6574329/how-can-i-produce-a-human-readable-difference-when-subtracting-two-unix-timestam) – siame Oct 09 '14 at 11:16
  • @JohnZwinck no the question did not answer, I will get year 1970 if I convert seconds from last_epoch - time.time() – Daniel Hyuuga Oct 09 '14 at 11:20
  • IMHO, a closer duplicate is this one: https://stackoverflow.com/questions/6574329/how-can-i-produce-a-human-readable-difference-when-subtracting-two-unix-timestam – sophros May 18 '21 at 11:03

2 Answers2

64
import datetime
timestamp = 1339521878.04 
value = datetime.datetime.fromtimestamp(timestamp)
print(value.strftime('%Y-%m-%d %H:%M:%S'))
pyprism
  • 2,928
  • 10
  • 46
  • 85
20
a = last_epoch #last epoch recorded
b = time.time() #current epoch time
c = b - a #returns seconds
days = c // 86400
hours = c // 3600 % 24
minutes = c // 60 % 60
seconds = c % 60
John Zwinck
  • 239,568
  • 38
  • 324
  • 436