paulzaba paulzaba - 1 year ago 134
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: continuation line missing indentation or outdented

Answer Source

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)]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download