How to limit lenght of a complicated line in Python?

223 views Asked by At

I'm formatting my code according to PEP8, but I have a little issue; this is it:

print ("DB Updated: " + datetime.datetime.fromtimestamp(int(stats_dict["db_update"])).strftime('%a %b %d %H:%M:%S %Y'))

How to break it into lines with 72-79 characters?

5

There are 5 answers

0
jfs On BEST ANSWER
from datetime import datetime

dt = datetime.fromtimestamp(int(stats_dict["db_update"]))
print("DB Updated: " + dt.strftime('%a %b %d %H:%M:%S %Y'))
0
Alex On
print ("DB Updated: " + datetime.datetime.fromtimestamp(\
     int(stats_dict["db_update"]))\
     .strftime('%a %b %d %H:%M:%S %Y'))
1
monkut On
timestamp = int(stats_dict["db_update"])
d = datetime.datetime.fromtimestamp(timestamp)
msg = "DB Updated: {}".format(d.strftime('%a %b %d %H:%M:%S %Y'))
print(msg)
1
georg On

I'd prefer:

print("DB Updated: " + 
    datetime.datetime.fromtimestamp(
        int(stats_dict["db_update"])
    ).strftime('%a %b %d %H:%M:%S %Y')
)

Note that you don't need line continuation symbols as long as the whole expression is in braces.

Temporary variables suck decrease readability, in my opinion.

OP's update: I modified your answer as follows:

 print("DB Updated: " +
      datetime.datetime.fromtimestamp(
        int(stats_dict["db_update"])).
        strftime('%a %b %d %H:%M:%S %Y'))
0
SilentGhost On
from datetime import datetime

dt = datetime.fromtimestamp(int(stats_dict["db_update"]))
print("DB Updated: {:%a %b %d %H:%M:%S %Y}".format(dt))