2

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.

SparkAndShine
  • 17,001
  • 22
  • 90
  • 134
Juan David
  • 2,676
  • 4
  • 32
  • 42
  • 1
    [Here's a similar post](http://stackoverflow.com/questions/4172448/is-it-possible-to-break-a-long-line-to-multiple-lines-in-python#4172465) that should help. Essentially you can escape newlines with a backslash. – The Maniac May 23 '16 at 18:26

2 Answers2

3

A pythonic way is using datetime module in order to get the date of 3 moth ago:

datetime.strftime(last_tx-timedelta(90),'%Y-%m-%d %H:%M:%S')

Here is an example:

>>> from datetime import datetime, timedelta
>>> datetime.now()
datetime.datetime(2016, 5, 23, 23, 3, 34, 588744)
>>> datetime.strftime(datetime.now()-timedelta(90),'%Y-%m-%d %H:%M:%S')
'2016-03-24 23:03:38'

As @ sparkandshine mentioned in comment, since 90 doesn't always represent 3 month you can use dateutil.relativedelta in order to achieve an exact match.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
2

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(months=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-02-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]))
SparkAndShine
  • 17,001
  • 22
  • 90
  • 134
  • I'm getting only two months of difference `2016-05-23 14:27:27 2016-03-23 14:27:27 2016-05-22 21:20:08 2016-03-22 21:20:08 2016-05-23 13:40:20 2016-03-23 13:40:20` ¿Do you know why? – Juan David May 23 '16 at 19:45
  • @JuanDavid, replace the argument `month` (absolute information) with `months` (relative information). – SparkAndShine May 23 '16 at 19:59