Python查找最新纪元时间并将其格式设置为字符串

Python查找最新纪元时间并将其格式设置为字符串,python,time,Python,Time,我正在使用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))

我正在使用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”对象没有属性“strftime”

您正在依次用
行[0]
的内容替换引用模块
时间的变量。只需将变量重命名为其他名称,即可避免名称空间冲突:

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))

您将依次用每行的
行[0]
的内容替换引用模块
时间的变量。只需将变量重命名为其他名称,即可避免名称空间冲突:

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)

如有关;;添加对空结果的处理(在本例中,当前代码返回历元)。

您可以简化代码:

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)

如有关;;添加对空结果的处理(在本例中,当前代码返回历元)。

Doh!不知道我怎么没看到。啊!不知道我怎么没看到。