Convert Date to Clock

I want to find the time difference between the two dates, and then compare the difference in hours. Something like that,

StartTime = 2011-03-10 15:45:48 EndTime = 2011-03-10 18:04:00

And then find the difference like, timeDifference = abs (StartTime - EndTime) And then I need to compare the results like, If timeDifference> 6 hours ...

When I use this method, the results obtained by me were in a time format, how can I change the time format to a clock in python?

Thanks,

+4
source share
1 answer

Suppose you have two dates and times as datetime objects (see datetime.datetime ):

 >>> import datetime >>> start_time = datetime.datetime(2011,3,10,15,45,48) >>> end_time = datetime.datetime(2011,3,10,18,4,0) 

Subtracting one datetime from another, you get a timedelta object, and you can use abs to provide a positive time difference:

 >>> start_time - end_time datetime.timedelta(-1, 78108) >>> abs(start_time - end_time) datetime.timedelta(0, 8292) 

Now, to convert the time difference from timedelta to hours, simply divide by 3600:

 >>> hours_difference = abs(start_time - end_time).total_seconds() / 3600.0 >>> hours_difference 2.3033333333333332 

Note that the total_seconds() method was introduced in Python 2.7, so if you want the earlier version you had to calculate it yourself from .days and .seconds , as in this answer

Update: Jochen Ritzel points out in a comment below that if it is just a comparison with a few hours that interest you, rather that the raw value, you can make it easier:

 abs(start_time - end_time) > timedelta(hours=6) 
+6
source

Source: https://habr.com/ru/post/1347435/


All Articles