$ cat .t.py
import re
from datetime import datetime as dtt
oldestDate = dateComp = dtt.strptime('1.1.1001', '%d.%m.%Y')
dateComp = dtt.strptime('11.1.2011', '%d.%m.%Y')
ind = re.sub(" days,.*", "", str((dateComp - oldestDate)))
print ind
print dateComp - oldestDate
$ python .t.py
368905
368905 days, 0:00:00
How can I get days only without the regex code-smell? The problem escalate because I need to use the index in many locations. So some cleaner way to do this?
Don’t use
str()so soon. The result you get back from subtracting onedatetimefrom another is atimedeltaobject, which has a.daysproperty that you can read.Note that reading only the
.daysproperty will mean that it will round down the difference – if you instead want to round to the nearest number of days, you’ll need to add some logic to check the.secondsproperty to see whether it’s closer to 0 or 86400.