0

I've written a small python script to determine the age of a record and if it is more than a week old. I do this by subtracting the record date from now(). The record returns the date 2016-02-23 09:01:22 as datetime.

now = datetime.datetime.now()
age = now - recordDate
print age

this prints the result as 71 days, 23:56:07.156000

Is there a more "pythonic" way to get it to output just the days (and no hours etc.) than my hack solution of

print str(age).split(',',1)[0]

which prints the result as 71 days?

Midavalo
  • 469
  • 2
  • 18
  • 29
  • unrelated: the local time may be non-linear. Don't use `datetime.now()` if you want to find the exact difference. See [Find if 24 hrs have passed between datetimes - Python](http://stackoverflow.com/q/26313520/4279). If you don't care about hours in your case; use `date.today()` instead. – jfs May 04 '16 at 21:27

1 Answers1

5

71 days, 23:56:07.156000 is a string representation of the timedelta object.

To get the days only, just get the, well, .days:

>>> from datetime import datetime
>>> 
>>> recordDate = datetime(year=2010, month=10, day=10)
>>> now = datetime.now()
>>> age = now - recordDate
>>> age  # age is the timedelta object
datetime.timedelta(2033, 61630, 853029)
>>> "%d days" % age.days
'2033 days'
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195