paulzaba paulzaba - 1 month ago 6
Python Question

How to indent this line for pep8 compatibility

How can I indent the line inside the for loop so that it is compatible with pep8?

for ii in range(len(file_time)):
file_time[ii] = datetime.strptime(str(file_date[ii]) + " " + str(file_time[ii]),'%Y/%m/%d %H:%M:%S.%f').replace(microsecond=0)


I've tried two of the options that the pep8 documentation offers:

# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
var_three, var_four)

# Hanging indents should add a level.
foo = long_function_name(
var_one, var_two,
var_three, var_four)


but I still get the same error:

script.py:36:9:E122 continuation line missing indentation or outdented

Answer

The hanging indent should work just fine:

for ii in range(len(file_time)):
    file_time[ii] = datetime.strptime(
        str(file_date[ii]) + " " + str(file_time[ii]),
        '%Y/%m/%d %H:%M:%S.%f').replace(microsecond=0)

You can improve on this by avoiding using str() conversions (you already have strings, surely), and using zip() and a list comprehension:

file_time = [
    datetime.strptime('{} {}'.format(fd, ft)
                      '%Y/%m/%d %H:%M:%S.%f').replace(microsecond=0)
    for fd, ft in zip(file_date, file_time)]

You can extract the conversion into a function too:

def as_dt(datestr, timestr, fmt='%Y/%m/%d %H:%M:%S.%f'):
    dt = datetime.strptime('{} {}'.format(fd, ft), fmt)
    return dt.replace(microsecond=0)

file_time = [as_dt(fd, ft) for fd, ft in zip(file_date, file_time)]
Comments