繁体   English   中英

Python查找最新纪元时间和格式为字符串

[英]Python Find Latest Epoch Time and Format As String

我正在使用Python在数据库中运行查询,并且我想返回列的最新纪元时间

import time
recent_time = 0
for row in rows:
    time = row[0]
    if time > recent_time:
        recent_time = int(time)
print "Latest Time: %s" % time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(recent_time))

但我不断得到AttributeError: 'long' object has no attribute 'strftime'

您将依次用每一行的row[0]内容替换引用模块time的变量。 只需将变量重命名为其他名称,就不会出现名称空间冲突:

import time
recent_time = 0
for row in rows:
    time_entry = row[0]
    if time_entry > recent_time:
        recent_time = int(time_entry)
print "Latest Time: %s" % time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(recent_time))

您可以简化代码:

import time

latest_time = max(int(row[0]) for row in rows) # find the latest epoch time
print(time.ctime(latest_time))                 # format as string (local time)

如果相关; 添加对空结果的处理(在这种情况下,您当前的代码将返回Epoch)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM