5

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.

Matthew W.
  • 413
  • 1
  • 9
  • 17

4 Answers4

5

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.

jfs
  • 399,953
  • 195
  • 994
  • 1,670
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • Thanks, that worked. Also the semicolons are a habit, coming for JS and PHP development. Doesn't seem to bring up errors or slow programs down so how bad is it? – Matthew W. Jun 10 '16 at 11:45
  • @MatthewMob: unrelated: you should use `utcnow()`, not `now()` here. – jfs Jun 10 '16 at 15:07
1

the statement

datetime.datetime.now() - date

yields a timedelta object. It has attributes like days or seconds etc.

DomTomCat
  • 8,189
  • 1
  • 49
  • 64
0

ANSWER

The datetime module in Python has got a function called timedelta. Delta in MATHS and in GREEK means difference. For example:

a = 1
b = 2
delta = b-a

so for answering to your question you have to write:

from datetime import date, timedelta
d = date.today() - timedelta(days=delta_days)

where delta_days are the days that you have to subtract.

dreamwhite
  • 116
  • 8
0

You don't need to convert it to datetime, you could get the current Unix time using time.time(). It allows to find the time difference in days given a Unix time from the past:

import time

DAY = 86400 # POSIX day - the exact value
days_ago = (time.time() - sub.created_utc) // DAY
jfs
  • 399,953
  • 195
  • 994
  • 1,670