简体   繁体   English

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

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

I am using Python to run a query in my database and I want to return the latest epoch time of a column 我正在使用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))

but I keep getting AttributeError: 'long' object has no attribute 'strftime' 但我不断得到AttributeError: 'long' object has no attribute 'strftime'

You are replacing the variable referencing the module time with the contents of row[0] for each row in turn. 您将依次用每一行的row[0]内容替换引用模块time的变量。 Simply rename your variable to something else so you don't get the namespace clash: 只需将变量重命名为其他名称,就不会出现名称空间冲突:

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

You could simplify your code: 您可以简化代码:

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)

If it is relevant; 如果相关; add handling of empty results (your current code returns Epoch in this case). 添加对空结果的处理(在这种情况下,您当前的代码将返回Epoch)。

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

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