One way is using a collections.deque
with max size 1 in order to get the last line then use str.split()
method in order to extract the time:
from collections import deque
with open(file_name) as f:
last_line = deque(f, maxlen=1).pop()
You can also use itertools.dropwhile()
in order to drop the lines of the file object (which is an iterator-like object) until they meet a certain criteria like based on the ends of lines.
from itertools import dropwhile
with open(file_name) as f:
last_line = next(dropwhile(lambda x: not x.endswith('G'), f))
# note that in aforementioned function supposed that all the lines ends with G (apparently, but all except the last line ends with newline)
In both method you van get the time like following:
time_string = last_line.rsplit(' ', 2)[0]
Or if you want to convert to time object, or timestamp
:
from datetime import datetime
datetime.strptime(time_string, '%Y-%m-%d %H:%M:%S')
datetime.strptime(a, '%Y-%m-%d %H:%M:%S').timestamp()