Convert String to Date row by row in a file with Python

I am new at python so I have question about it. There is a file "x.list" in /data01/test directory. And it is linux OS.

This file contains;

 "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

what I try to make is;

 "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

Third column should be the Start time- End time

1 answer

  • answered 2019-01-11 05:26 knh190

    Make use of regex and datetime:

    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)
    

    Reference:

    1. Converting string into datetime
    2. https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior