Issue
I have two columns with start and end dates;[A snippet of the columns][1] S
ervice Start Day Service Completion Day
2015-02-16 2015-02-16
2015-06-17 2015-06-18
2015-06-06 2015-06-06
2015-08-08 2015-08-08
2015-08-03 2015-08-21
2015-07-25 2015-07-25
2015-08-17 2015-08-17
2015-07-30 2015-09-24
I want to calculate the difference between all these dates,row-wise and place them in another column.
I tried doing it in ths manner;
Df['Service Completion Day'] = date(Df['Service Completion Day'])
Df['Service Request Day'] = date(Df['Service Request Day'])
Df.assign(Days = Df['Service Completion Day'] - Df['Service Request Day'])
But this is not working.
Is there a way to do this?
Solution
As input, you are having two strings, e.g. '2015-02-12'
and '2015-02-16'
. You should parse them into datetime.date
objects and then calculate the difference.
For example:
import datetime
date_string_1 = '2015-02-12'
date_string_2 = '2015-02-16'
date1 = datetime.datetime.strptime(date_string_1, '%Y-%m-%d').date()
date2 = datetime.datetime.strptime(date_string_2, '%Y-%m-%d').date()
print (date2-date1) # prints: 4 days, 0:00:00
difference_in_days = (date2-date1).days
print(difference_in_days) # prints: 4
Answered By - zvone
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.