1

I have two date features of type datetime. I'd like to express the difference between them in days cast as type int. How do I accomplish this:

In[]
print lcd.time_to_default
print lcd.issue_date

lcd['time_to_default']=(lcd.last_pymnt_date - lcd.issue_date)

lcd.time_to_default.head()

Out[92]:
datetime64[ns]
datetime64[ns]

0   1127 days
1    487 days
2    913 days
3   1127 days
4   1217 days
Name: time_to_default, dtype: timedelta64[ns]

I want to cast this series as an int, not timedelta64.

Addendum: I can't cast this as ".days" as the link above which supposes a duplicate, suggests.

In[] lcd.time_to_default.days

Returns: Out[] 'Series' object has no attribute 'days'

GPB
  • 2,395
  • 8
  • 26
  • 36

3 Answers3

1

Just subtract the two datetime variables. That yields timedelta type.

Eg:

In [2]: datetime.datetime.now()
Out[2]: datetime.datetime(2015, 6, 2, 0, 30, 49, 548657)

In [3]: yesterday = datetime.datetime.now() - datetime.timedelta(days=1)

In [4]: datetime.datetime.now() -  yesterday
Out[4]: datetime.timedelta(1, 17, 32459)

In [5]: diff = (datetime.datetime.now() -  yesterday)

In [6]: diff.days
Out[6]: 1
sirfz
  • 4,097
  • 23
  • 37
Hitesh Dharamdasani
  • 852
  • 1
  • 10
  • 19
0

Try this,

>>> from datetime import datetime
>>> date1 = datetime(2015,6,2)
>>> date2 = datetime(2015,5,2)
>>> diff = date1 - date2
>>> print (diff.days)
31
Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61
  • But I can't cast the series as .days. The line: lcd['time_to_default']= (lcd.last_pymnt_date - lcd.issue_date).days Returns the error: 'Series' object has no attribute 'days' – GPB Jun 01 '15 at 19:14
  • can you help by looking at my comment above? – GPB Jun 01 '15 at 19:43
0

To get integer number of days from a series of timedelta64[ns], you could try (not tested):

result = np.divide(lcd.time_to_default, np.timedelta64(1, 'D')) 

See Time difference in seconds from numpy.timedelta64 and Converting between datetime, Timestamp and datetime64.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670