不使用time.second获得第二名

时间:2015-09-11 01:22:28

标签: python

python的新手,让我说我有

t = "2008-12-12 19:21:10"

如何在不使用

的情况下获得第二个
t.second 

也不是

int(t[-2:])

2 个答案:

答案 0 :(得分:1)

一种方法是拆分:

t = "2008-12-12 19:21:10"
seconds = int(t.split(':')[-1])
print(seconds) # prints 10

另一个简单的正则表达式:

import re
t = "2008-12-12 19:21:10"
seconds = int(re.search(r'(\d+)\Z',t).group(1))
print(seconds) # prints 10

使用箭头可以这样做:

import arrow
t = "2008-12-12 19:21:10"
seconds = int(arrow.get(t, 'YYYY-MM-DD HH:mm:ss').format('ss'))
print(seconds) # prints 10

同样使用datetime.strptime.strftime:

t = "2008-12-12 19:21:10"
seconds = int(datetime.strptime(t, '%Y-%m-%d %H:%M:%S').strftime('%S'))
print(seconds) # prints 10

或更简单(如果允许):

seconds = datetime.strptime(t, '%Y-%m-%d %H:%M:%S').second
print(seconds) # prints 10

答案 1 :(得分:0)

或者您的老朋友正则表达式:

import re
m = re.match("([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})", t)
seconds = int(m.group(6))