I have two different dates and I want to know the difference in days between them. The format of the date is YYYY-MM-DD.
I have a function that can ADD or SUBTRACT a given number to a date:
def addonDays(a, x):
ret = time.strftime("%Y-%m-%d",time.localtime(time.mktime(time.strptime(a,"%Y-%m-%d"))+x*3600*24+3600))
return ret
where A is the date and x the number of days I want to add. And the result is another date.
I need a function where I can give two dates and the result would be an int with date difference in days.
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)
Another short solution:
from datetime import date
def diff_dates(date1, date2):
return abs(date2-date1).days
def main():
d1 = date(2013,1,1)
d2 = date(2013,9,13)
result1 = diff_dates(d2, d1)
print '{} days between {} and {}'.format(result1, d1, d2)
print ("Happy programmer's day!")
main()
You can use the third-party library dateutil, which is an extension for the built-in datetime.
Parsing dates with the parser module is very straightforward:
from dateutil import parser
date1 = parser.parse('2019-08-01')
date2 = parser.parse('2019-08-20')
diff = date2 - date1
print(diff)
print(diff.days)
Answer based on the one from this deleted duplicate
I tried the code posted by larsmans above but, there are a couple of problems:
1) The code as is will throw the error as mentioned by mauguerra
2) If you change the code to the following:
...
d1 = d1.strftime("%Y-%m-%d")
d2 = d2.strftime("%Y-%m-%d")
return abs((d2 - d1).days)
This will convert your datetime objects to strings but, two things
1) Trying to do d2 - d1 will fail as you cannot use the minus operator on strings and
2) If you read the first line of the above answer it stated, you want to use the - operator on two datetime objects but, you just converted them to strings
What I found is that you literally only need the following:
import datetime
end_date = datetime.datetime.utcnow()
start_date = end_date - datetime.timedelta(days=8)
difference_in_days = abs((end_date - start_date).days)
print difference_in_days
Try this:
data=pd.read_csv('C:\Users\Desktop\Data Exploration.csv')
data.head(5)
first=data['1st Gift']
last=data['Last Gift']
maxi=data['Largest Gift']
l_1=np.mean(first)-3*np.std(first)
u_1=np.mean(first)+3*np.std(first)
m=np.abs(data['1st Gift']-np.mean(data['1st Gift']))>3*np.std(data['1st Gift'])
pd.value_counts(m)
l=first[m]
data.loc[:,'1st Gift'][m==True]=np.mean(data['1st Gift'])+3*np.std(data['1st Gift'])
data['1st Gift'].head()
m=np.abs(data['Last Gift']-np.mean(data['Last Gift']))>3*np.std(data['Last Gift'])
pd.value_counts(m)
l=last[m]
data.loc[:,'Last Gift'][m==True]=np.mean(data['Last Gift'])+3*np.std(data['Last Gift'])
data['Last Gift'].head()
I tried a couple of codes, but end up using something as simple as (in Python 3):
from datetime import datetime
df['difference_in_datetime'] = abs(df['end_datetime'] - df['start_datetime'])
If your start_datetime and end_datetime columns are in datetime64[ns] format, datetime understands it and return the difference in days + timestamp, which is in timedelta64[ns] format.
If you want to see only the difference in days, you can separate only the date portion of the start_datetime and end_datetime by using (also works for the time portion):
df['start_date'] = df['start_datetime'].dt.date
df['end_date'] = df['end_datetime'].dt.date
And then run:
df['difference_in_days'] = abs(df['end_date'] - df['start_date'])
pd.date_range('2019-01-01', '2019-02-01').shape[0]
Related
I am currently trying to construct a function that takes a date string and returns the number of days from that date until now. It will return 0 if it detects that the format is wrong, with the input date string format being Day/Month/Year (e.g. 12/3/21). The number should be negative if it is a past date (e.g. today is 14/3/21, the input date is 3/3/21, the function should return -11). This is my code so far but it keeps returning 0:
from datetime import datetime
from datetime import date
def convert_date(input_date):
try:
current_date = date.today()
d1 = datetime.strptime(input_date, '%d/%m/%y')
d2 = datetime.strptime(current_date, '%d/%m/%y')
delta = d1 - d2
return delta.day
except:
return 0
I am very unsure on what I have done wrong, as I have done a lot of research but have not found a solution. Hopefully someone can provide further clarification, thanks
(Also i am using the Datetime package)
These are basics and you need to understand datetime module well. Hope this solves your problem.
from datetime import datetime
def convert_date(input_date):
try:
current_date = datetime.today()
d1 = datetime.strptime(input_date, '%d/%m/%y')
delta = d1 - current_date
return delta.days
except ValueError:
return 0
So I have todays date in dd.mm.yy format like this:
today = datetime.datetime.today()
today_betterform = today.strftime("%d.%m.%y")
now I have a date in the same format as above and I want a variable with the number of days between today and then.
How would I go about doing this?
You need to convert both dates to datetime type:
d1 = datetime.datetime.strptime(input(), "%d.%m.%y")
d2 = datetime.datetime.today()
Then, compute their difference:
difference = d2 - d1
And divide it by one day:
difference_in_days = difference / datetime.timedelta(days=1)
Now, difference_in_days is the number of days between d1 and d2.
I wouldn't recommend transforming your today variable to a string.
To get the difference in days, you should just subtract two datetime objects from each other.
import datetime
# setup dates
previous_date = datetime.datetime.strptime("05-27-2018", '%m-%d-%Y')
today = datetime.datetime.today()
# compute difference
ndays = (today - previous_date).days
# print output
print(ndays)
This outputs
173
Hi I have two times in slightly different formats and I need to work out the difference. The first was parsed from a ISO 8601 date using dateutil.parser
I'm not sure what I need to do to parse them into the same format, but my two dates are:
2017-05-24 15:40:00+00:00
2017-05-24 14:23:44.995015
If they were both in datetime format I could just subtract one from the other, so I need to chop the milliseconds off both (coz that's not relevant to me), and tell python the new strings are both datetimes?
Since you're already using dateutil, what's wrong with just removing the timezone (or adding it to the other) and subtracting them?
import dateutil.parser
date1 = dateutil.parser.parse("2017-05-24 15:40:00+00:00").replace(tzinfo=None)
date2 = dateutil.parser.parse("2017-05-24 14:23:44.995015")
date_delta = date1 - date2 # 1:16:15.004985
You can call replace(microsecond=0) on your dates to remove the microseconds.
You could transform the second datetime (that is a timestamp) into the first one with this code:
def convert_to_timestamp(string_date):
the_datetime = datetime.strptime(string_date.decode("utf-8"), "%Y%m%d.%H%M%S.%f")
return time.mktime(the_datetime.timetuple()) * 1e6 + the_datetime.microsecond
or:
def transformTimestamps(timestamp_):
year = timestamp_[:4]
month = timestamp_[4:6]
day = timestamp_[6:8]
hour = timestamp_[9:11]
minute = timestamp_[11:13]
second = timestamp_[13:15]
microsecond = timestamp_[16:22]
myformat = year+"-"+month+"-"+day+" +hour+":"+minute+":"+second+":"+microsecond
return datetime.strptime(myformat, '%Y-%m-%d %H:%M:%S:%f')
Then, you can calculate the difference between them.
I hope this help. Greetings!
Probably you want to use this method
datetime.strptime(date_string, format)
Also remember you can get rid of elements you do not want in your date (Like milliseconds) when you declare the specified date, as in
class datetime.datetime(year, month, day, hour=0, minute=0, second=0,
microsecond=0, tzinfo=None, *, fold=0)
For more on this topic you can always read the python docs, you can find the same information I just gave you and more here:
https://docs.python.org/3/library/datetime.html
Hope it helped.
I have looked around to see if I can find a simple method in Python to find out if a date has passed.
For example:-
If the date is 01/05/2015, and the date; 30/04/2015 was in-putted into Python, it would return True, to say the date has passed.
This needs to be as simple and efficient as possible.
Thanks for any help.
you may use datetime, first parse String to date, then you can compare
import datetime
d1 = datetime.datetime.strptime('05/01/2015', "%d/%m/%Y").date()
d2 = datetime.datetime.strptime('30/04/2015', "%d/%m/%Y").date()
d2>d1
from datetime import datetime
present = datetime.now()
print datetime(2015,04,30) < present #should return true
Sourced some material from this question/answer: How to compare two dates?
Just compare them?
>>> t1 = datetime.datetime.now()
>>> t2 = datetime.datetime.now()
>>> t1>t2
False
>>> t1<t2
True
You can create a simple function which does this:
def has_expired(date):
import datetime
return date < datetime.datetime.now()
I would like to be able to do greater than and less than against dates. How would I go about doing that? For example:
date1 = "20/06/2013"
date2 = "25/06/2013"
date3 = "01/07/2013"
date4 = "07/07/2013"
datelist = [date1, date2, date3]
for j in datelist:
if j <= date4:
print j
If I run the above, I get date3 back and not date1 or date2. I think I need I need to get the system to realise it's a date and I don't know how to do that. Can someone lend a hand?
Thanks
You can use the datetime module to convert them all to datetime objects. You are comparing strings in your example:
>>> from datetime import datetime
>>> date1 = datetime.strptime(date1, "%d/%m/%Y")
>>> date2 = datetime.strptime(date2, "%d/%m/%Y")
>>> date3 = datetime.strptime(date3, "%d/%m/%Y")
>>> date4 = datetime.strptime(date4, "%d/%m/%Y")
>>> datelist = [date1, date2, date3]
>>> for j in datelist:
... if j <= date4:
... print(j.strftime('%d/%m/%Y'))
...
20/06/2013
25/06/2013
01/07/2013
You are comparing strings, not dates. You should use a date-based object-type, such as datetime.
How to compare two dates?
You can use the datetime module:
>>> from datetime import datetime
>>> d = datetime.strptime(date4, '%d/%m/%Y')
>>> for j in datelist:
... d1 = datetime.strptime(j, '%d/%m/%Y')
... if d1 <= d:
... print j
...
20/06/2013
25/06/2013
01/07/2013
The problem with your comparison is that a string comparison first compares the first character, followed by the second one, and the third, and so on. You can of course convert the strings to dates, like the other answers suggest, but there is a different solution as well.
In order to compare dates as strings you need to have them in a different format like : 'yyyy-mm-dd'. In this way it first compares the year, than the month and finally the day:
>>> d1 = '2012-10-11'
>>> d2 = '2012-10-12'
>>> if d2 > d1:
... print('this works!')
this works!
The advantages of this are simplicity (for me at least) and performance because it saves the conversion of strings to dates (and possibly back) while still reliably comparing the dates. In programs I use I compare dates a lot as well. Since I take the dates from files it are always strings to begin with, and because performance is an issue with my program I normally like to compare dates as strings in this way.
Of course this would mean you would have to convert your dates to a different format, but if that is a one time action, it could well be worth the effort.. :)