如何比较python中持有datetime.strptime值的两个变量?

时间:2015-10-10 15:59:16

标签: python

我正在尝试与保留date.strptime值的变量进行比较。问题是我似乎为这两个变量获得了nameerror

for line in x[25:34]:
    if '2 DATE' in line:
        pos= line.find('E')
        host= line[pos+1:17]

        #print 'James Birth Date is:', (convert_date)

for line1 in x [90:99]:
     if '2 DATE' in line1:
        pos1 = line1.find('E')
        host1= line1[pos1+1:17]

    convert_date= datetime.strptime (host,'%d %b %Y').date()
    convert_date1= datetime.strptime (host, '%d %b %Y').date()

    if (convert_date > convert_date1):
        print ' James was born before he got married'

我可能做错了什么?

1 个答案:

答案 0 :(得分:0)

您似乎遇到了scope

的问题
for line in x[25:34]:
    if '2 DATE' in line:
        pos= line.find('E')
        host= line[pos+1:17]

#here host and pos don't exist anymore

在循环之前定义它们:

pos = None
host = None
for line in x[25:34]:
    if '2 DATE' in line:
        pos= line.find('E')
        host= line[pos+1:17]

# pos and host do exist, and if they're not None, they have been set