If I have two dates (ex. \'8/18/2008\'
and \'9/26/2008\'
), what is the best way to get the number of days between these two dates?
It also can be easily done with arrow
:
import arrow
a = arrow.get('2017-05-09')
b = arrow.get('2017-05-11')
delta = (b-a)
print delta.days
For reference: http://arrow.readthedocs.io/en/latest/
You want the datetime module.
>>> from datetime import datetime, timedelta
>>> datetime(2008,08,18) - datetime(2008,09,26)
datetime.timedelta(4)
Another example:
>>> import datetime
>>> today = datetime.date.today()
>>> print(today)
2008-09-01
>>> last_year = datetime.date(2007, 9, 1)
>>> print(today - last_year)
366 days, 0:00:00
As pointed out here
everyone has answered excellently using the date, let me try to answer it using pandas
dt = pd.to_datetime('2008/08/18', format='%Y/%m/%d')
dt1 = pd.to_datetime('2008/09/26', format='%Y/%m/%d')
(dt1-dt).days
This will give the answer. In case one of the input is dataframe column. simply use dt.days in place of days
(dt1-dt).dt.days
Using the power of datetime:
from datetime import datetime
date_format = "%m/%d/%Y"
a = datetime.strptime('8/18/2008', date_format)
b = datetime.strptime('9/26/2008', date_format)
delta = b - a
print delta.days # that's it
Without using datetime object in python.
# A date has day 'd', month 'm' and year 'y'
class Date:
def __init__(self, d, m, y):
self.d = d
self.m = m
self.y = y
# To store number of days in all months from
# January to Dec.
monthDays = [31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31 ]
# This function counts number of leap years
# before the given date
def countLeapYears(d):
years = d.y
# Check if the current year needs to be considered
# for the count of leap years or not
if (d.m <= 2) :
years-= 1
# An year is a leap year if it is a multiple of 4,
# multiple of 400 and not a multiple of 100.
return int(years / 4 - years / 100 + years / 400 )
# This function returns number of days between two
# given dates
def getDifference(dt1, dt2) :
# COUNT TOTAL NUMBER OF DAYS BEFORE FIRST DATE 'dt1'
# initialize count using years and day
n1 = dt1.y * 365 + dt1.d
# Add days for months in given date
for i in range(0, dt1.m - 1) :
n1 += monthDays[i]
# Since every leap year is of 366 days,
# Add a day for every leap year
n1 += countLeapYears(dt1)
# SIMILARLY, COUNT TOTAL NUMBER OF DAYS BEFORE 'dt2'
n2 = dt2.y * 365 + dt2.d
for i in range(0, dt2.m - 1) :
n2 += monthDays[i]
n2 += countLeapYears(dt2)
# return difference between two counts
return (n2 - n1)
# Driver program
dt1 = Date(31, 12, 2018 )
dt2 = Date(01, 01, 2019 )
print(getDifference(dt1, dt2), "days")
Here are three ways to go with this problem :
from datetime import datetime
Now = datetime.now()
StartDate = datetime.strptime(str(Now.year) +'-01-01', '%Y-%m-%d')
NumberOfDays = (Now - StartDate)
print(NumberOfDays.days) # Starts at 0
print(datetime.now().timetuple().tm_yday) # Starts at 1
print(Now.strftime('%j')) # Starts at 1