Python - 将自纪元时间以秒为单位转换为人类可读时间

24

最初我编写了这段代码来将日期转换为易于理解的时间:

    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

我正在尝试使用epoch时间,但我不知道如何计算天数、小时等。

    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

1
这个答案应该会对你有所帮助:如何使用Python计算两个UNIX时间戳之间的人类可读差异? - siame
@JohnZwinck 不,这个问题没有得到解答。如果我将从last_epoch - time.time()转换的秒数,我会得到1970年。 - Daniel Hyuuga
在我看来,更接近的副本是这个:https://dev59.com/m2w15IYBdhLWcg3wfr5x - sophros
2个回答

64
import datetime
timestamp = 1339521878.04 
value = datetime.datetime.fromtimestamp(timestamp)
print(value.strftime('%Y-%m-%d %H:%M:%S'))

3
最便捷的方式,键入更少的内容,且对错误更加坚韧。 - miguelmorin
1
datetime.datetime.fromtimestamp(timestamp).isoformat() is much more convenient than futzing with strftime - ijoseph

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

谢谢!最方便的方法是不使用额外的Python模块。 - Daniel Hyuuga

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接