2016-05-23 96 views
2

字符串長字符串

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)) 

作品沒有問題,但我想知道是否有某種方式的漂亮格式的更多appropiately重新寫這個(在Python的方式)。 last_tx是一個日期時間對象。

+1

[這裏是一個類似的帖子](http://stackoverflow.com/questions/4172448/is-it-possible-to-break-a-long-line-to-multiple-lines-in-python#4172465)這應該有所幫助。基本上你可以用反斜線來換行。 –

回答

2

更Python的方式是使用dateutil.relativedelta(聲明3個月)和datetime.strftime(格式日期時間)。這是一個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 

以前的答案,使用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])) 
+0

我只差兩個月了'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'你知道爲什麼嗎? –

+0

@JuanDavid,用'months'(相對信息)替換參數'month'(絕對信息)。 – SparkAndShine

3

一個Python的方式是使用datetime模塊,以獲得3蛾前日期:

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

這裏一個例子:

>>> 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' 

由於@ sparkandshine在評論中提到,由於90並不總是代表3個月,所以您可以使用dateutil.relativedelta以實現完全匹配。

+1

90天('timedelta(90)')並不總是相當於3個月。使用'relativedelta(month = 3)'更好嗎? – SparkAndShine

+1

@sparkandshine的確,感謝您的留言;) – Kasramvd

+1

感謝您在答案中提及我。你贏得了我的讚賞:-) – SparkAndShine