【问题标题】:Python - Convert seconds from epoch time into human readable time [duplicate]Python - 将纪元时间的秒数转换为人类可读的时间[重复]
【发布时间】:2014-12-04 07:03:48
【问题描述】:

最初我编写这段代码是为了将日期转换为人类可读的时间:

    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

我正在尝试使用纪元时间,但我不知道如何让它计算天数等。

    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

【问题讨论】:

标签: python time


【解决方案1】:
import datetime
timestamp = 1339521878.04 
value = datetime.datetime.fromtimestamp(timestamp)
print(value.strftime('%Y-%m-%d %H:%M:%S'))

【讨论】:

  • 最好的便捷方式,输入更少,对错误更稳健。
  • datetime.datetime.fromtimestamp(timestamp).isoformat() 比使用strftime 更方便
【解决方案2】:
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 模块的最佳便捷方式
猜你喜欢
  • 2012-08-16
  • 2013-01-13
  • 2013-03-17
  • 2021-03-30
  • 2018-12-13
  • 2020-09-29
  • 2017-04-06
  • 2012-11-12
相关资源
最近更新 更多