0

I have two strings in python.

time_array1='09-JAN-2014 01:19'
time_array2='09-JAN-2014 01:01'

I need to find the time difference and I am doing:

print time_array1
print time_array2
FMT = '%d-%m-%Y %H:%M'
datetime_object1= datetime.datetime.strptime(time_array1, FMT)
print datetime_object1
datetime_object2= datetime.datetime.strptime(time_array2, FMT)
print datetime_object2
diff=datetime_object1 - datetime_object2
print diff

but I am getting the following error:

    datetime_object1= datetime.datetime.strptime(time_array1, FMT)
AttributeError: type object 'datetime.datetime' has no attribute 'strptime'

Is there any alternative way through which I can do it. It seems the python library doesn't have strptime attribute.

1
  • What version of Python are you using? The function was added in Python 2.5. Commented Mar 21, 2014 at 13:00

1 Answer 1

1

The strptime method was added in python 2.5; if you are using an older version use the following code instead:

import datetime, time
datetime_object1 = datetime.datetime(*time.strptime(time_array1, FMT)[:6])

Your months are abbreviations, use the %b to parse that instead of %m.

Demo:

>>> import datetime, time
>>> time_array1='09-JAN-2014 01:19'
>>> time_array2='09-JAN-2014 01:01'
>>> FMT = '%d-%b-%Y %H:%M'
>>> datetime.datetime(*time.strptime(time_array1, FMT)[:6])
datetime.datetime(2014, 1, 9, 1, 19)
>>> datetime.datetime(*time.strptime(time_array2, FMT)[:6])
datetime.datetime(2014, 1, 9, 1, 1)
Sign up to request clarification or add additional context in comments.

4 Comments

The time_array1 and timearray2 are not constant. The code wherein I'll take the insert_ts from database and take the difference between two consecutive insert_ts. So time_array1 and time_array2 will be changing. Now when I did datetime_object1=datetime.datetime(*time.strptime(time_array1, FMT)[:6]) I got 2014-03-21 12:04:00 and and when I did datetime_object2= datetime.datetime(*time.strptime(time_array2, FMT)[:6]) I got 2014-03-21 12:12:00 and I did the diff which gave me 0:08:00 but I got an error in script saying : ValueError: time data did not match format: data=X X fmt=%d-%b-%Y %H:%M
Looks like you have data in your database that is not consistent. Either there is a row that uses a different format or is not a date altogether. Try catching the exception and printing the string that caused the parse to fail.
Yes got the error. some of the data is coming as 'X X' as part of the insert_ts.
Clearly that's not a value that can be pasted into a datetime object. You'll need to adjust your code to skip those.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.