Skip to content Skip to sidebar Skip to footer

Why The Below Program When Subtracting With One Another Providing "-1 Day, 23:59:58.233000" Kind Of Output?

I am trying to subtract two timestamps using datetime library of python. Since I don't want date to be included, I removed the date part from below code. Everything comes perfect i

Solution 1:

you can write your own converter, to get a nice display of timedelta objects. Ex:

from datetime import datetime

d1 = datetime.strptime('12:10:05.1',"%H:%M:%S.%f")
d2 = datetime.strptime('13:10:05.2',"%H:%M:%S.%f")

c=(d1-d2)
print(c)
# -1 day, 22:59:59.900000deftimedeltaToString(td):
    total, prefix = td.total_seconds(), ""if total<0: # catch negative timedelta
        total *= -1
        prefix = "-"
    hours, remainder = divmod(total, 3600)
    minutes, seconds = divmod(remainder, 60)
    returnf"{prefix}{int(hours):02d}:{int(minutes):02d}:{seconds:09.6f}"print(timedeltaToString(c))
# -01:00:00.100000

Related: Format timedelta to string

Solution 2:

In the simplest way you can compare the dates. Suppose you have columns from_date and to_date. if from_date >= to_date then take from_date - to_date otherwise take to_date - from_date.

# assuming you have two columns as from_date and to_date
df['from_date'] = pd.to_datetime(df['from_date'])
df['to_date'] = pd.to_datetime(df['to_date'])


df['date_difference']  = df[['from_date', 'to_date']].apply(lambda x: (x[0]-x[1]) if (x[0]>=x[1]) else (x[1]-x[0]), axis=1)

Once you have got the timedelta, you can get all required information, for example, if you want to get only days then

df['date_difference'].dt.days

Full list found here

Post a Comment for "Why The Below Program When Subtracting With One Another Providing "-1 Day, 23:59:58.233000" Kind Of Output?"