Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get difference in days between today's date and previous date

I'm using the "datetime" module and I'm trying to work out the difference between two dates in days. Here's the code that I'm using, with some other code coming before it that gets the object sub.created_utc (a POSIX timestamp, or unix timestap):

import datetime

date = datetime.datetime.utcfromtimestamp(sub.created_utc);
print(sub.created_utc);
print(date);
print(datetime.datetime.now() - date);

and here is the output:

1440736746.0
2015-08-28 04:39:06
287 days, 16:47:41.560711

My question is, how do I get the 287 days part of that (or just 287, I don't mind either way). I know I could use regex to just extract that part of it, but is there a better more reliable way of doing it?

Thanks for any help! If you want me to give the full code I can provide it, just wouldn't think it would be necessary.

like image 419
Matthew W. Avatar asked Jun 10 '16 11:06

Matthew W.


People also ask

How do I calculate the difference between today and another date in Excel?

What'll you need to do is subtract today's date from the project start date. Excel has a TODAY function built in, which will save you from typing in the date in the correct format and continually updating as the days change. So, the formula is: =TODAY() – B2.


1 Answers

Once you subtract the dates, you get a datetime.timedelta object, and you can access its properties directly:

import datetime

d1 = datetime.datetime.utcfromtimestamp(sub.created_utc)
print(sub.created_utc)
print(d1)
result = datetime.datetime.utcnow() - d1
print(result.days)

Python statements don't end in ;; and date is the name of a built-in library; so best not to use it in your code.

like image 68
Burhan Khalid Avatar answered Nov 14 '22 21:11

Burhan Khalid