Daniel Plas Rivera Daniel Plas Rivera - 1 year ago 130
Python Question

detect a timestamp string in a list

I'm trying to detect if a timestamp string is in a list and send its value to result if it's present and if it's not I want result to be "NONE". I've got this so far. The the timestamp always changes btw. How would I rewrite this to work?

lists = ['405',3 ,'2014-12-06 14:08:58.990377', '\\N']

for i in range(len(lists)):
if lists[i] == ?????:
result = lists[i].split('.')[0]
result = "NONE"

Answer Source

For each element of a list use strptime to test if it's in a format you consider a timestamp. strptime will throw a ValueError if it's unable to parse a string. If it is able to parse it, you set is as a result, else as "NONE.

Something like this:

from datetime import datetime

for element in lists:
        # If this line doesn't throw an Error, it's indeed a timestamp in proper format.
        datetime.strptime(element, "%Y-%m-%d %H:%M:%S.%f")
        result = element
    except (ValueError, TypeError):
        result = "NONE"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download