Working with time in pandas and python

Asked

Viewed 1,116 times

-2

I have a dataFrame in which two columns are of the type datetime.time and I need to subtract one from the other and get the value in minutes.

To turn into datetime.time did so:

gcr['hora_inicio_atividade'] = pd.to_datetime(gcr['hora_inicio_atividade'],format= '%H:%M:%S').dt.time

gcr['data_saida'] = pd.to_datetime(gcr['data_saida'],format= '%H:%M:%S').dt.time

When I go to create a new field with subtraction of the two above the interpreter accuses the following error:

Typeerror: Unsupported operand type(s) for -: 'datetime.time' and datetime.time'

1 answer

4

There is no difference between times. It makes no sense.

If I ask you what the difference is between 11:00:00 and 10:00:00 you may even get attack to reply that it is 1 hour, but it is wrong, because the time 11:00:00 is the day 25/12/2025, while the time 10:00:00 is the day 01/03/1993. The interval between these two instants is much greater than just 1 hour.

However, did you notice that it was only because I also mentioned the date that it made sense to analyze the time interval? That is, analyzing the interval between time instants of defined dates is perfectly plausible. That is, rather than subtracting objects of the type datetime.time, subtraction datetime.datetime.

from datetime import datetime

final = datetime.strptime('11:45:13', '%H:%M:%S')
inicial = datetime.strptime('10:30:07', '%H:%M:%S')

intervalo = final - inicial

print(intervalo)  # 1:15:06

But keep the date?

By default, the module datetime will use the date 1900-01-01 as reference and, if you do not explicitly inform, it will be that date that will be considered. Thus, in the example, you would be analyzing the interval between 1900-01-01 11:45:13 and 1900-01-01 10:30:07. As they are same day times, it doesn’t matter much if the date is correct or not, but if you need different dates you will need to explicitly inform.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.