user8042669
user8042669

Reputation:

How to convert datetime64 array to int?

With this

pd.Timestamp("31.12.1999 23:59:12").value
>>946684752000000000

I can get the integer value of a datetime elementary value.

How can I get this done for an array of datetime values?

df = pd.DataFrame({"a": ["31.12.1999 23:59:12", "31.12.1999 23:59:13", "31.12.1999 23:59:14"], "b": [4, 5, 6]})
df.insert(0, 'date', df.a.apply(lambda x: datetime.datetime.strptime(x, "%d.%m.%Y %H:%M:%S")))

Apparently, this does not work:

df.date.values.value
>>AttributeError: 'numpy.ndarray' object has no attribute 'value'

Upvotes: 11

Views: 17700

Answers (1)

jezrael
jezrael

Reputation: 862641

Use to_datetime with converting to np.int64:

df['int'] = pd.to_datetime(df['a']).astype(np.int64)

print (df)
                     a  b                 int
0  31.12.1999 23:59:12  4  946684752000000000
1  31.12.1999 23:59:13  5  946684753000000000
2  31.12.1999 23:59:14  6  946684754000000000

Upvotes: 14

Related Questions