I'm extracting a string from a SSH connection output, which gives me a string like '3d02h' and I have to insert this date into a database.
The output is from the command "show spanning-tree detail | inc ieee|occurr|from|is exec" executed in a cisco_switch, which gave me the following output:
VLAN0001 is executing the ieee compatible Spanning Tree protocol Number of topology changes 490 last change occurred 3d02h ago from GigabitEthernet1/0/11
So I used .split() function to extract the '3d02h' from the output.
Now I want to convert the string into a datetime object.
I've tried to use datetime.strptime(string, "%d %H") to extract the day and the hour from the string but it doesn't work.
I've done it with re and parsedatetime.
from datetime import datetime
import parsedatetime as pdt
import re
cal = pdt.Calendar()
print(datetime.now())
date = "3d02h"
index = 2
date = re.findall(r'[A-Za-z]+|\d+', date)
date_len = int(len(date))
date_len = date_len // 2
for item in range(0, date_len):
date.insert(index, ' ago ')
index += 3
date = "".join(date)
print(date)
date, flags = cal.parseDT(date)
assert flags
print(date)
The output is:
2019-09-05 13:37:28.710065
3d ago 02h ago
2019-09-02 11:37:28