2016-05-23 99 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