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'
1

1 Answer

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest