Juan David Juan David - 6 months ago 21
Python Question

Pretty formatting of long string

The string

date2check = to_datetime(str(last_tx.year) + \
'-' + str(int(last_tx.month)-3) + \
'-' + str(last_tx.day) + \
' ' + str(last_tx.hour) + \
':' + str(last_tx.minute) + \
':' + str(last_tx.second))


works without problem but I want to know if there is some way to re-write this more appropiately (in a pythonic way).
last_tx
is a datetime object.

Answer

A more pythonic way is to use dateutil.relativedelta (declare 3 months) and datetime.strftime (format datetime). Here is a MWE.

from datetime import datetime
from dateutil.relativedelta import relativedelta

three_months = relativedelta(month=3) 
dt = datetime.now() - three_months  # replace `datetime.now()` with `last_tx`

s = dt.strftime('%Y-%m-%d %H:%M:%S')

print(s)
# Output
2016-03-23 20:37:19

Previous answer, Use str.join,

s1 = '-'.join([str(i) for i in [last_tx.year, last_tx.month-3, last_tx.day])
s2 = ':'.join([str(i) for i in [last_tx.hour, last_tx.minute, last_tx.second])

date2check = to_datetime(' ',join([s1, s2]))