Calculate with different datetime formats, datetime and datetime64

375 Views Asked by At

I am trying to calculate the days between two dates:

First Date:

date = datetime.datetime.today() # {datetime} 2018-09-17 14:42:06.506541

Second date, extracted from a data frame:

date2 = data_audit.loc[(data_audit.Audit == audit), 'Erledigungsdatum'].values[0]
# {datetime64} 2018-07-23T00:00:00.000000000

The error:

ufunc subtract cannot use operands with types dtype('O') and dtype('M8[ns]')

My next try was:

date = np.datetime64(datetime.datetime.now()) # {datetime64} 2018-09-17T14:48:16.599541

Which resulted in the following error (I pass the date as a parameter in a function):

ufunc 'bitwise_and' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

How should I approach this problem? The second one seems more logical to me, but I don't understand why I cant pass a simple date to a function.

2

There are 2 best solutions below

0
On

Let's try such approach

import datetime
date  = datetime.datetime.today()
date2 = '2018-07-23'#here could be your date converted to proper type
date2 = datetime.datetime.strptime(date2, '%Y-%m-%d')
difference = date- date2
difference = difference.days

And you can apply df.some_col_with_difference.astype('timedelta64[D]') to whole column in dataframe as well

1
On

I believe something like this should work for you:

import datetime
import numpy as np

# earlier being of type datetime64
earlier = np.datetime64(datetime.datetime.today())
# Converting datetime64 to datetime
earlier = earlier.astype(datetime.datetime)
now = datetime.datetime.today()

print(now-earlier)