Stripping time from a string to calculate elapsed time

Hello,
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 = datetime.today()

print a, ENTER, b, ENTER, b - a
exit()
``````
2 Likes

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.

3 Likes

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

1 Like

@GoToLoop @tabreturn
Thank you for the above code (a while ago) for using the datetime routines, working well for my sketches written using Processing Python mode, .
Instead of Python mode, I now want to do the same coding in Processing (version 3.5.4) but unsure of the syntax to import datetime and subsequent calls to strip dates, as above.
For example, when I replaced ‘from datetime import datetime’ in Python mode
with ‘import datetime’ or ‘import datetime.*’ in Processing mode,
I get an error message: The package “datetime” does not exist. You might be missing a library…no Library found for datetime

Any tips and sample code in Processing appreciated, thanks.

2 Likes

To add to @GoToLoop’s response –

The `datetime` is a Python module. You’ll have to import the necessary java modules, something like this:

``````import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

LocalDate dateA = LocalDate.parse("2011-01-01");
LocalDate dateB = LocalDate.parse("2021-02-01");
print(ChronoUnit.DAYS.between(dateA, dateB));
``````
2 Likes