Difference between two dates in Python
Use -
to get the difference between two datetime
objects and take the days
member.
from datetime import datetime
def days_between(d1, d2):
d1 = datetime.strptime(d1, "%Y-%m-%d")
d2 = datetime.strptime(d2, "%Y-%m-%d")
return abs((d2 - d1).days)
How to calculate number of days between two given dates
If you have two date objects, you can just subtract them, which computes a timedelta
object.
from datetime import date
d0 = date(2008, 8, 18)
d1 = date(2008, 9, 26)
delta = d1 - d0
print(delta.days)
The relevant section of the docs:
https://docs.python.org/library/datetime.html.
See this answer for another example.
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.
Find time difference between two dates in python
import datetime
dt_str_a = '2020-06-29 16:15:27'
dt_str_b = '2020-07-12 12:00:00'
dt_a = datetime.datetime.strptime(dt_str_a, '%Y-%m-%d %H:%M:%S')
dt_b = datetime.datetime.strptime(dt_str_b, '%Y-%m-%d %H:%M:%S')
print(dt_b - dt_a)
print((dt_b - dt_a).days)
->
12 days, 19:44:33 # <---- precise value
12 # <---- number of days only
Difference between two dates (datetime)
You can simply parse the time using the appropriate strptime format.
Then, once you’ve obtained two date
objects, you can simply subtract them:
import datetime
d1_str = "Apr 29 2020"
d2_str = "May 7 2020"
fmt = "%b %d %Y"
d1 = datetime.datetime.strptime(d1_str, fmt).date()
d2 = datetime.datetime.strptime(d2_str, fmt).date()
delta = d2 - d1
print(delta)
print(delta.days)
Output is:
6 days, 0:00:00
6
How to find difference between two dates which are in string format in Python?
You can try this:
from datetime import datetime
A = '24 06 2020 12:45'
B = '14 05 2020 12:45'
A = datetime.strptime(A,"%d %m %Y %H:%M")
B = datetime.strptime(B,"%d %m %Y %H:%M")
To get hours
from seconds
as follows:
print((A - B).total_seconds() // 3600)
I just added '//' instead of '/' for dividing so that I get the exact Number of hours
Calculate difference between two dates in python
You can convert two columns to datetime type then subtract at last get hours from timedelta object.
df['date1'] = pd.to_datetime(df['date1'])
df['date2'] = pd.to_datetime(df['date2'])
df['diff'] = (df['date1']-df['date2']) / pd.Timedelta(hours=1)
how can i calculate the difference between two dates and times in python
Ignoring how listaDivisa is constructed in OP's code then this may help:
from datetime import datetime
ON = 'ON'
OFF = 'OFF'
listaDivisa = [['2009-10-16', '21:06:34.00044', 'kitchen sensor', 'ON'],
['2009-10-16', '21:13:22.00016', 'kitchen sensor', 'OFF'],
['2009-10-16', '12:53:29', 'bathroom sensor', 'ON'],
['2009-10-16', '14:02:51.00056', 'bathroom sensor', 'OFF']]
results = {}
for date_, time_, sensor_, state_ in listaDivisa:
for fmt in '%Y-%m-%d%H:%M:%S.%f', '%Y-%m-%d%H:%M:%S':
try:
results.setdefault(sensor_, {})[state_] = datetime.strptime(f'{date_}{time_}', fmt)
break
except ValueError:
pass
for k, v in results.items():
if ON in v and OFF in v:
print(k, (v[OFF]-v[ON]).seconds)
Output:
kitchen sensor 407
bathroom sensor 4162
Related Topics
Repeating Elements of a List N Times
How to Append One String to Another in Python
How to Trim Whitespace from a String
Working with Big Data in Python and Numpy, Not Enough Ram, How to Save Partial Results on Disc
What's the Deal with Python 3.4, Unicode, Different Languages and Windows
How to Convert This List of Dictionaries to a CSV File
Convert Utf-8 with Bom to Utf-8 with No Bom in Python
Adding a Module (Specifically Pymorph) to Spyder (Python Ide)
Obtain Active Window Using Python
How to Run Python Code from Sublime Text 2
How to Properly Subclass Dict and Override _Getitem_ & _Setitem_
Multiprocessing: Understanding Logic Behind 'Chunksize'
Python Sharing a Lock Between Processes
Text with Unicode Escape Sequences to Unicode in Python
Numpy Matrix Vector Multiplication
Django 1.7 Throws Django.Core.Exceptions.Appregistrynotready: Models Aren't Loaded Yet