简体   繁体   中英

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

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'

You are replacing the variable referencing the module time with the contents of row[0] for each row in turn. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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