1

I have two string objects:

dt1[1]="00:58:00"    
dt2[1]="01:02:00"

If I do,

FMT='%H:%M:%S'
SD=datetime.datetime(*time.strptime(dt1[1], FMT)[:6])
FD=datetime.datetime(*time.strptime(dt2[1], FMT)[:6])

it translates to 1900-01-01 00:58:00 and 1900-01-01 01:02:00 but I want only the time part not the date.

I have converted date into string and subtracted only the time part from it. Now i need to convert them to time object again and do dt2[1]-dt[1] to find the time difference.

How can I do it.

1 Answer 1

2

To get datetime.time() objects, just call the datetime.datetime.time() method on the result:

>>> import datetime
>>> import time
>>> dt1 = '00:58:00'
>>> dt2 = '01:02:00'
>>> FMT='%H:%M:%S'
>>> datetime.datetime(*time.strptime(dt1, FMT)[:6])
datetime.datetime(1900, 1, 1, 0, 58)
>>> datetime.datetime(*time.strptime(dt1, FMT)[:6]).time()
datetime.time(0, 58)
>>> datetime.datetime(*time.strptime(dt2, FMT)[:6]).time()
datetime.time(1, 2)

However, if you are going to subtract these, use the datetime.datetime() objects! You cannot subtract datetime.time() objects:

>>> res1 = datetime.datetime(*time.strptime(dt1, FMT)[:6])
>>> res2 = datetime.datetime(*time.strptime(dt2, FMT)[:6])
>>> res2.time() - res1.time()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'
>>> res2 - res1
datetime.timedelta(0, 240)
Sign up to request clarification or add additional context in comments.

7 Comments

I need to subtract only time part. If I subtract date object it will give me 1 day something the original objects are having dates like this : 03-APR-2014 00:58 02-APR-2014 01:02 so if i subtract it, it will show 23 hr something, but i only need to subtract hour and minute part like 01:02 - 00:58 and it will give me 4 mins.
@Debayan: I know, but if you need to subtract the times, you need datetime objects. It doesn't matter for your usecase that the dates an those objects are useless; only that they are the same date.
I can even convert them entirely to minutes and subtract it.
@Debayan: sure, but that'd require a different method of parsing; the time and datetime modules don't deal in durations but in fixed points in time (date, or date + time or time of day) instead.
So any idea how to find the time difference
|

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.