How to limit lenght of a complicated line in Python?
-
22-07-2021 - |
Question
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?
Solution
from datetime import datetime
dt = datetime.fromtimestamp(int(stats_dict["db_update"]))
print("DB Updated: " + dt.strftime('%a %b %d %H:%M:%S %Y'))
OTHER TIPS
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)
from datetime import datetime
dt = datetime.fromtimestamp(int(stats_dict["db_update"]))
print("DB Updated: {:%a %b %d %H:%M:%S %Y}".format(dt))
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'))
print ("DB Updated: " + datetime.datetime.fromtimestamp(\
int(stats_dict["db_update"]))\
.strftime('%a %b %d %H:%M:%S %Y'))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow