使用Python将文件中的字符串逐行转换为日期

使用Python将文件中的字符串逐行转换为日期,python,redhat,Python,Redhat,我是python新手,所以我对它有疑问。 在/data01/test目录中有一个文件“x.list”。这就是linux操作系统 该文件包含: "A2","Start Time; 2019-01-10T00:00:18Z, EndTime;2019-01-10T00:13:57Z" "A3","Start Time; 2019-01-10T00:57:26Z, EndTime;2019-01-10T00:59:26Z" "A4","Start Time; 2019-01-10T00:14:2

我是python新手,所以我对它有疑问。 在/data01/test目录中有一个文件“x.list”。这就是linux操作系统

该文件包含:

 "A2","Start Time; 2019-01-10T00:00:18Z, EndTime;2019-01-10T00:13:57Z"
 "A3","Start Time; 2019-01-10T00:57:26Z, EndTime;2019-01-10T00:59:26Z"
 "A4","Start Time; 2019-01-10T00:14:29Z, EndTime;2019-01-10T00:22:29Z
我想做的是

 "A2","2019-01-10 00:13:57, 00:13:39  
 "A3","2019-01-10 00:59:49, 00:2
 "A4","2019-01-10 00:22:13, 00:8

第三列应该是开始时间-结束时间

使用正则表达式和日期时间:

import re
from datetime import datetime

start, end = re.findall(r'(\d+-\d+-\d+)T(\d+:\d+:\d+)Z', line)
start_time = datetime.striptime(' '.join(start), '%Y-%m-%d %H:%M:%S')
end_time = datetime.striptime(' '.join(end), '%Y-%m-%d %H:%M:%S')

print(start_time.strftime('%Y-%m-%d %H:%M:%S'))
print(end_time.strftime('%Y-%m-%d %H:%M:%S'))

# delta time can be found like this
# format as you need, see above for example
delta = end_time - start_time
print(delta)
参考: