TypeError: unsupported operand type(s) for -: 'str' and 'datetime.datetime'
Question: I am working on my python script to get the list of date format from the
sqlite database.

I'm creating the variable `startDelta` to get the list of rows from the
variable called `program_startDate`.

When I use this statement to execute the code, I get a problem with my code:

    
    
    #get the programs list
    cur.execute('SELECT channel, title, start_date, stop_date FROM programs 
    WHERE channel=?', [channel])
    programList = list()
    programs = cur
    
    for row in programs:
         program = row[1].encode('ascii'), str(row[2]), str(row[3])
         program_startDate = str(row[2])
         program_endDate = str(row[3])
         programList.append(program)
    cur.close()
    
    idx = str(programList)
    
    # find nearest half hour
    viewStartDate = datetime.datetime.now()
    viewStartDate -= datetime.timedelta(minutes = viewStartDate.minute % 30, 
    seconds = viewStartDate.second)
    
    startDelta = program_startDate - viewStartDate
    stopDelta = program_endDate - viewStartDate
    

I will get an error: TypeError: unsupported operand type(s) for -: 'str' and
'datetime.datetime'

The errors are jumping on this line:

    
    
    startDelta = program_startDate - viewStartDate
    stopDelta = program_endDate - viewStartDate
    

How to fix this?


Answer: The problem is exactly as the error states. `program_startDate` and
`program_endDate` are strings, and you're trying to subtract a datetime from
them, something python is unable to do.

Are these values stored as datetimes in your database?

If so, use:

    
    
     program_startDate = row[2]
     program_endDate = row[3]
    

Instead of converting them to strings. The db engine will get them as datetime
for you and the error will be solved.

If they're stored as strings in your db, [use
datetime.strptime](https://docs.python.org/2/library/datetime.html#strftime-
strptime-behavior) to convert them to datetimes according to the format
they're stored in.

Edit:

The OP is storing dates as long in the database, such as 20140831170500. To
solve the problem, use:

    
    
    from datetime import datetime
    ...
    ...
    for row in programs:
        program = row[1].encode('ascii'), str(row[2]), str(row[3])
        program_startDate = datetime.strptime(str(row[2]), '%Y%m%d%H%M%S')
        program_endDate = datetime.strptime(str(row[3]), '%Y%m%d%H%M%S')
        programList.append(program)
    

