Reputation: 37
I need to find the time difference between date/time TrackLogs on a table using a for loop. The trackLog entries are found in the following format:
2013-08-02T14:30:10Z
I need to take into consideration that the 'for' loop fails when it tries to calculate the first timediff. because the first log has no preceding entry to execute the calculation. Therefore I need to include an 'if' statement (with a boolean) to allow the script to run when it finds the first log.
This is what I have got so far:
for row in cur:
period=row.tracklogs
year=period[0:4]
month=period[6:7]
day=period[8:10]
hour=period[11:13]
minut=period[14:16]
second=period[17:19]
print period
firstline="yes"
if firstline=="yes":
prev_period=row.tracklogs
prev_coord=row.shape
firstline="no"
else:
new_period=row.tracklogs
new_coord=row.shape
period1=datetime.datetime(int(prev_period))
period2=datetime.datetime(int(new_period))
timediff=(a2-a1).seconds
print timediff
I think I need an integer for the datetime operation but then I run into the following exception:
line 36, in <module>
tid1=datetime.datetime(int(tidl_tid))
ValueError: invalid literal for int() with base 10: '2009-05-19T11:51:47Z'
I know I'm doing something wrong but can't tell what it is. Any help m appreciated.
Upvotes: 0
Views: 1254
Reputation: 76907
You are trying to convert a string 2009-05-19T11:51:47Z
to integer, where the string is not a proper base 10 number. So python is throwing up the error
You need to parse your date strings and obtain the necessary datetime objects.
Assuming
date_string = "2009-05-19T11:51:47Z"
Either do
from dateutil import parser
d1 = parser.parse(date_string)
or
from datetime import datetime
d1 = datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%SZ")
And use the next command to get the difference between two dates d1 and d2 in seconds
(d1-d2).total_seconds()
Upvotes: 1