Daniel Plas Rivera
Daniel Plas Rivera

Reputation: 400

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]
    else:
        result = "NONE"

Upvotes: 1

Views: 2628

Answers (1)

Rok Povsic
Rok Povsic

Reputation: 4895

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:
    try:
        # 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"

Upvotes: 4

Related Questions