Stripping time from a string to calculate elapsed time

I would like to calculate elapsed time based on start and end times (extracted from an XML file)
startDate=“2016-11-16 09:26:33 +1000” endDate="2016-11-16 09:26:33
As the times are embedded in a string(see above),
I think

  • firstly, I need to extract the start and end times into hour, minute, seconds variables from the string
    for example., hour from 12th position, length 2 (please help with Python syntax to do this, thanks)
  • then convert hour, minute & second into seconds
  • then calculate difference in seconds

Regards, Paul

1 Like

from datetime import datetime

a = datetime(2016, 11, 16, 9, 26, 33, 1000)
b =

print a, ENTER, b, ENTER, b - a

I’m not sure what the “+1000” part is for? Anyhow, here’s some code that should do it for you:

from datetime import datetime

startDate = '2016-11-16 09:26:33 +1000'
endDate = '2016-11-16 09:26:33'

# strip-off the +1000 part
startPlus = startDate[startDate.index('+')+1:] # 1000
startDate = startDate[:-len(startPlus)-2] # 2016-11-16 09:26:33

# convert start date to datetime format
startDate = datetime.strptime(startDate, '%Y-%m-%d %H:%M:%S')

# convert end date to datetime format
endDate = datetime.strptime(endDate, '%Y-%m-%d %H:%M:%S')

# difference is zero seconds, but you can fiddle with the initial variables
print( (startDate-endDate).total_seconds() )

I’ve stripped-off the +1000 part, but stored the 1000 in the startPlus variable if you need it.


Thank you for your replies with coding plus attachments (extra info.)
@tabreturn @GoToLoop
all very useful and contribute to the progress of my program.