Andrea
Andrea

Reputation: 748

Python Subtracting Only a Time (HH:MM:SS) from a DateTime Column

I have a column of DateTimes in a pandas dataframe. I would like to subtract a start time from these DateTimes. The start time would be on the same day as each of the DateTimes. This cannot be done with the following small reproducible example:

import datetime
start_day = datetime.time(18, 30, 0) # 18:30:00 is the start time
datetime_object = datetime.datetime.now()
datetime_object.time() - start_day

TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'

It isn't ideal for me to split the dateTimes into separate date and time columns in order to do this calculation. What are my alternatives?

Thank you

Edit:

Sample DataFrame and Expected Output:

Room In DateTime      Desired Output (minutes)
2015-10-18 19:30:00   60
2015-10-18 21:39:00   99

Upvotes: 1

Views: 1006

Answers (3)

dvaraujo
dvaraujo

Reputation: 46

The previous answers are correct. Just to clarify:

When working with dates, operations between two datetime objects will return a timedelta object (because is the difference of time between them), and operations between a datetime object and a time delta will returna a datetime object. To summarize, read the following words as objects of a type:

datetime + datetime = timedelta

datetime + timedelta = datetime

Some more reproducible code:

Operation between a datetime object and a timedelta object

from datetime import datetime, timedelta
today = datetime.today()

print(today)
datetime.datetime(2019, 9, 27, 13, 26, 50, 972445)

print(str(today))
'2019-09-27 13:26:50.972445'

print(type(today))
<class 'datetime.datetime'>

yesterday = today - timedelta(days=1)
print(yesterday)
datetime.datetime(2019, 9, 26, 13, 26, 50, 972445)

print(str(yesterday))
'2019-09-26 13:26:50.972445'

print(type(yesterday))
<class 'datetime.datetime'>

Operation between two datetime objects

today - yesterday
datetime.timedelta(days=1)

str(today - yesterday)
'1 day, 0:00:00'

type(today-yesterday)
<class 'datetime.timedelta'

Hope this helps :)

Upvotes: 2

Massifox
Massifox

Reputation: 4487

Symply use datetime.timedelta. Try this code:

import datetime
start_day = datetime.timedelta(hours=2, minutes=30)
datetime_object = datetime.datetime.now()     # 2019-09-27 18:23:06.684283
datetime_object - start_day                   # 2019-09-27 15:53:06.684283 

Upvotes: 1

John Gordon
John Gordon

Reputation: 33335

Can you use timedelta instead?

import datetime
datetime_object = datetime.datetime.now()
datetime_object - datetime.timedelta(hours=2, minutes=30)
2019-09-27 08:36:43.463856

Upvotes: 1

Related Questions