Subtract two times to get a duration Python
Date 20-07-2020
- day-month-year
can't match to your %m-%d-%Y
which means month-day-year
. You have wrong order of day
and month
. So you have to use %d-%m
instead of %m-%d
BTW: you have to caluculate stop - start
instead of start - stop
from datetime import datetime
start = '20-07-2020 11:00:00'
stop = '20-07-2020 13:30:00'
format_date = "%d-%m-%Y %H:%M:%S"
dt_start = datetime.strptime(start, format_date)
dt_stop = datetime.strptime(stop, format_date)
duration = dt_stop - dt_start
print(f'Start: {dt_start}, Stop: {dt_stop}')
print(duration)
Result
Start: 2020-07-20 11:00:00, Stop: 2020-07-20 13:30:00
2:30:00
To format it you need to get total seconds and calculate hours, minutes, seconds
rest = duration.total_seconds()
hours = int(rest // (60*60))
rest = rest % (60*60)
minutes = int(rest // 60)
seconds = int(rest % 60)
print(f"{hours} hours, {minutes} minutes, {seconds} seconds")
Result
2 hours, 30 minutes, 0 seconds
Or you have to convert duration to string and then split it
hours, minutes, seconds = str(duration).split(':')
print(f"{hours} hours, {minutes} minutes, {seconds} seconds")
Result
2 hours, 30 minutes, 00 seconds
BTW: when you convert duration
to string then it runs code similar to my calculations with total_seconds
- I checked this in source code.
Python - Calculate the difference between two datetime.time objects
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
How to calculate the time interval between two time strings
Yes, definitely datetime
is what you need here. Specifically, the datetime.strptime()
method, which parses a string into a datetime
object.
from datetime import datetime
s1 = '10:33:26'
s2 = '11:15:49' # for example
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
That gets you a timedelta
object that contains the difference between the two times. You can do whatever you want with that, e.g. converting it to seconds or adding it to another datetime
.
This will return a negative result if the end time is earlier than the start time, for example s1 = 12:00:00
and s2 = 05:00:00
. If you want the code to assume the interval crosses midnight in this case (i.e. it should assume the end time is never earlier than the start time), you can add the following lines to the above code:
if tdelta.days < 0:
tdelta = timedelta(
days=0,
seconds=tdelta.seconds,
microseconds=tdelta.microseconds
)
(of course you need to include from datetime import timedelta
somewhere). Thanks to J.F. Sebastian for pointing out this use case.
How do I find the time difference between two datetime objects in python?
>>> import datetime
>>> first_time = datetime.datetime.now()
>>> later_time = datetime.datetime.now()
>>> difference = later_time - first_time
datetime.timedelta(0, 8, 562000)
>>> seconds_in_day = 24 * 60 * 60
>>> divmod(difference.days * seconds_in_day + difference.seconds, 60)
(0, 8) # 0 minutes, 8 seconds
Subtracting the later time from the first time difference = later_time - first_time
creates a datetime object that only holds the difference.
In the example above it is 0 minutes, 8 seconds and 562000 microseconds.
Python, subtract two different times in the format (HH:MM:SS - HH:MM:SS)
You need strptime
method from datetime
.
import datetime
format = '%m/%d/%y %H:%M:%S'
startDateTime = datetime.datetime.strptime(message.start, format)
endDateTime = datetime.datetime.strptime(message.end, format)
diff = endDateTime - startDateTime
output:
>>> start='08/11/16 12:00:00'
>>> format = '%m/%d/%y %H:%M:%S'
>>> startDateTime = datetime.datetime.strptime(start, format)
>>> end='08/11/16 18:30:00'
>>> endDateTime = datetime.datetime.strptime(end, format)
>>> diff = endDateTime - startDateTime
>>> print diff
6:30:00
Subtract time only from two datetime columns in Pandas
You need to set both datetimes to a common date first.
One way is to use pandas.DateOffset
:
o = pd.DateOffset(day=1, month=1, year=2022) # the exact numbers don't matter
# reset dates
ts1 = df['ts1'].add(o)
ts2 = df['ts2'].add(o)
# subtract
df['ts_delta'] = ts2.sub(ts1)
As one-liner:
df['ts_delta'] = df['ts2'].add((o:=pd.DateOffset(day=1, month=1, year=2022))).sub(df['ts1'].add(o))
Other way using a difference between ts2-ts1 (with dates) and ts2-ts1 (dates only):
df['ts_delta'] = (df['ts2'].sub(df['ts1'])
-df['ts2'].dt.normalize().sub(df['ts1'].dt.normalize())
)
output:
ts1 ts2 ts_delta
0 2018-07-25 11:14:00 2018-07-27 12:14:00 0 days 01:00:00
1 2018-08-26 11:15:00 2018-09-24 10:15:00 -1 days +23:00:00
2 2018-07-29 11:17:00 2018-07-22 11:00:00 -1 days +23:43:00
NB. don't get confused by the -1 days +23:00:00
, this is actually the ways to represent -1hour
How can I subtract two date time values in a Pandas Dataframe
Convert your columns to actual dates first:
df['ALARM_DATE'] = pd.to_datetime(df['ALARM_DATE'])
df['CONT_DATE'] = pd.to_datetime(df['CONT_DATE'])
Or:
df[['ALARM_DATE', 'CONT_DATE']] = df[['ALARM_DATE', 'CONT_DATE']].apply(pd.to_datetime)
Output:
>>> df['CONT_DATE'] - df['ALARM_DATE']
0 5 days
1 3 days
2 -162 days
3 1 days
4 5 days
dtype: timedelta64[ns]
Related Topics
Force Python to Forego Native SQLite3 and Use the (Installed) Latest SQLite3 Version
How to Generate an HTML Directory List Using Python
How Is the Feature Score(/Importance) in the Xgboost Package Calculated
Convert Backward Slash to Forward Slash in Python
Ruby Equivalent to Python's Help()
What Is the Good Python3 Equivalent for Auto Tuple Unpacking in Lambda
How to Make the Python Interpreter Correctly Handle Non-Ascii Characters in String Operations
Running Windows Shell Commands with Python
What Does % Do to Strings in Python
Understand the Find() Function in Beautiful Soup
R, Python: Install Packages on Rpy2
Output Seckeycopyexternalrepresentation