在列表
检测时刻字符串我试图检测一个时刻字符串是在列表中,并发送其值设置为结果,如果它的现在,如果它不是我想要的结果是“无”。到目前为止我已经得到了这个。时间戳总是随着btw变化。我将如何重写这个工作?在列表
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" 
回答:
对于列表中的每个元素使用strptime来测试,如果它在你考虑时间戳的格式。如果它无法解析字符串,则strptime将抛出ValueError。如果它能够解析它,您将是作为一个结果,否则为“NONE
事情是这样的:
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" 
以上是 在列表 的全部内容, 来源链接: utcz.com/qa/261307.html




