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 to calculate number of days between two dates
http://momentjs.com/ or https://date-fns.org/
From Moment docs:
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // =1
or to include the start:
a.diff(b, 'days')+1 // =2
Beats messing with timestamps and time zones manually.
Depending on your specific use case, you can either
- Use
a/b.startOf('day')
and/ora/b.endOf('day')
to force the diff to be inclusive or exclusive at the "ends" (as suggested by @kotpal in the comments). - Set third argument
true
to get a floating point diff which you can thenMath.floor
,Math.ceil
orMath.round
as needed. - Option 2 can also be accomplished by getting
'seconds'
instead of'days'
and then dividing by24*60*60
.
How to calculate number of days between two dates?
Here is a quick and dirty implementation of datediff
, as a proof of concept to solve the problem as presented in the question. It relies on the fact that you can get the elapsed milliseconds between two dates by subtracting them, which coerces them into their primitive number value (milliseconds since the start of 1970).
// new Date("dateString") is browser-dependent and discouraged, so we'll write// a simple parse function for U.S. date format (which does no error checking)function parseDate(str) { var mdy = str.split('/'); return new Date(mdy[2], mdy[0]-1, mdy[1]);}
function datediff(first, second) { // Take the difference between the dates and divide by milliseconds per day. // Round to nearest whole number to deal with DST. return Math.round((second-first)/(1000*60*60*24));}
alert(datediff(parseDate(first.value), parseDate(second.value)));
<input id="first" value="1/1/2000"/><input id="second" value="1/1/2001"/>
Finding the number of days between two dates
$now = time(); // or your date as well
$your_date = strtotime("2010-01-31");
$datediff = $now - $your_date;
echo round($datediff / (60 * 60 * 24));
count the number of days between two dates per year
Here's one approach using tidyverse
and lubridate
.
First, separate the rows by calendar year, to use to measure the number of days for each year. Each row will include dates to be counted in each calendar year, starting with January 1st and ending with December 31st if overlapping multiple years. Then, it is easy to calculate the number of days in a given year.
The results from this example are slightly different than what I have. Year 2016 is a leap year and has 366 days. If the number of days are not inclusive of either start or end dates, you would get a different answer.
library(tidyverse)
library(lubridate)
df %>%
mutate(date_int = interval(start, end),
year = map2(year(start), year(end), seq)) %>%
unnest(year) %>%
mutate(year_int = interval(as.Date(paste0(year, '-01-01')), as.Date(paste0(year, '-12-31'))),
year_sect = intersect(date_int, year_int),
start_new = as.Date(int_start(year_sect)),
end_new = as.Date(int_end(year_sect))) %>%
select(id, start_new, end_new) %>%
mutate(year = year(start_new),
days = as.numeric(end_new - start_new)) %>%
right_join(df) %>%
pivot_wider(id_cols = c(id, start, end), names_from = year, values_from = days, names_prefix = "year_", values_fill = list(days = 0)) %>%
mutate(days_number = reduce(select(., starts_with("year_")), `+`))
Output
id start end year_2015 year_2016 days_number
<dbl> <date> <date> <dbl> <dbl> <dbl>
1 1 2015-01-01 2016-12-31 364 365 729
2 2 2016-01-01 2016-12-31 0 365 365
3 3 2015-07-01 2016-12-31 183 365 548
Calculate days between two dates given specific values
def dayDiff(groupby):
if (not (groupby.Yes == 1).any()) or (not (groupby.Value > 0).any()):
return np.zeros(groupby.Date.count())
min_date = groupby[groupby.Yes == 1].Date.iloc[0]
max_date = groupby[groupby.Value > 0].Date.iloc[0]
delta = max_date - min_date
return np.where(groupby.Value > 0 , delta.days, 0)
df1.Date = pd.to_datetime(df1.Date, dayfirst=True)
DateDiff = df1.groupby('UserId').apply(dayDiff).explode().rename('DateDiff').reset_index(drop=True)
pd.concat([df1, DateDiff], axis=1)
Returns:
Date UserId Value Yes DateDiff
0 2017-01-02 1 0 1 0
1 2017-01-03 1 0 0 0
2 2017-01-04 1 0 0 0
3 2017-01-05 1 100 0 3
4 2017-01-01 2 0 1 0
5 2017-01-02 2 1000 0 1
6 2017-01-03 2 0 0 0
Although this answers your question, the date diff
logic is hard to follow, especially when it comes to the placement of the DateDiff
values.
Update
pd.Series.explode()
was only introduced in pandas
version 0.25
, for those using previous versions:
df1.Date = pd.to_datetime(df1.Date, dayfirst=True)
DateDiff = (df1
.groupby('UserId')
.apply(dayDiff)
.to_frame()
.explode(0)
.reset_index(drop=True)
.rename(columns={0: 'DateDiff'}))
pd.concat([df1, DateDiff], axis=1)
This will yield the same results.
calculate number of 'Real' days between two dates when given a number of business days as input
For business days over 5 days you can take the business day, divide by 5 and make at an integer (floor), multiply by 7, and add the modulus of business days and 5. E.g for 26/5 => 5 (weeks) * 7 = 35 + 1 (modulus of 26 and 5) = 36
For under 5 days you will need some logic to check the day of the week for your current and to see if it does cross a weekend or not, and add 2 if it does.
Related Topics
Efficient Way to Rotate a List in Python
Pandas: How to Easily Share a Sample Dataframe Using Df.To_Dict()
Sort a List by Multiple Attributes
Annotate Bars With Values on Pandas Bar Plots
How to Select a Variable by (String) Name
Is Explicitly Closing Files Important
Reading Binary File and Looping Over Each Byte
Can't Pickle ≪Type 'Instancemethod'≫ When Using Multiprocessing Pool.Map()
Delete a Column from a Pandas Dataframe
Permanently Add a Directory to Pythonpath
Word Boundary With Words Starting or Ending With Special Characters Gives Unexpected Results
Equivalent of Shell 'Cd' Command to Change the Working Directory