Python - Calculate the difference between two date

2020-05-19 06:26发布

I have two datetime.time objects and I want to calculate the difference in hours between them. For example

a = datetime.time(22,00,00)
b = datetime.time(18,00,00)

I would like to be able to subtract these so that it gives me the value 4.

3条回答
老娘就宠你
2楼-- · 2020-05-19 06:42

I got my result from this problem:

a='2017-10-10 21:25:13'

b='2017-10-02 10:56:33'

a=pd.to_datetime(a)

b=pd.to_datetime(b)

c.total_seconds()/3600

but in series that wont work:

table1['new2']=table1['new'].total_seconds()/3600
查看更多
Emotional °昔
3楼-- · 2020-05-19 06:43

This is how I did

a = '2200'
b = '1800'
time1 = datetime.strptime(a,"%H%M") # convert string to time
time2 = datetime.strptime(b,"%H%M") 
diff = time1 -time2
diff.total_seconds()/3600    # seconds to hour 

output: 4.0

查看更多
▲ chillily
4楼-- · 2020-05-19 06:49

To calculate the difference, you have to convert the datetime.time object to a datetime.datetime object. Then when you subtract, you get a timedelta object. In order to find out how many hours the timedelta object is, you have to find the total seconds and divide it by 3600.

# Create datetime objects for each time (a and b)
dateTimeA = datetime.datetime.combine(datetime.date.today(), a)
dateTimeB = datetime.datetime.combine(datetime.date.today(), b)
# Get the difference between datetimes (as timedelta)
dateTimeDifference = dateTimeA - dateTimeB
# Divide difference in seconds by number of seconds in hour (3600)  
dateTimeDifferenceInHours = dateTimeDifference.total_seconds() / 3600
查看更多
登录 后发表回答