17

I would like to convert

['17-10-2010 07:15:30', '13-05-2011 08:20:35', "15-01-2013 09:09:09"]

into a Numpy datetime object.

import numpy as np
[np.datetime64(x) for x in ['17-10-2010 07:15:30', '13-05-2011 08:20:35', "15-01-2013 09:09:09"]] 

raised ValueError: Could not convert object to NumPy datetime. However, the following works as I intended

[np.datetime64(x) for x in ['2010-10-17 07:15:30', '2011-05-13 08:20:35', "2012-01-15 09:09:09"]] 

How can I convert my array into a format that conforms with Numpy's datetime64 function requirement?

I am using Numpy version 1.7.0. in python 3.4

2 Answers 2

24

So far as I can tell, np.datetime64 only works with

strings in ISO 8601 date or datetime format

The to_datetime function in pandas seems to be more flexible:

import pandas as pd
a=pd.to_datetime(['17-10-2010 07:15:30', '13-05-2011 08:20:35', "15-01-2013 09:09:09"])

Of course you can easily convert back to numpy:

np.array(a,dtype=np.datetime64)
Sign up to request clarification or add additional context in comments.

2 Comments

np.array(a,dtype=np.datetime64) is great but it returns '17-10-2010T07:15:30', how to make it '17-10-2010 07:15:30' ?
"The to_datetime function in pandas seems to be more flexible", but in that case, be aware of the date/time nightmare in pandas
2

np.datetime64 works with format yyyy-mm-dd hh:mm:ss

If you have a list of 5-6 elements you can directly make use of np.datetime64 data type by just changing the format(yyyy-mm-dd hh:mm:ss) of date in your list

for example:

dates=['17-10-2010 07:15:30', '13-05-2011 08:20:35', "15-01-2013 09:09:09"]
#to
dates=['2010-10-17 07:15:30', '2011-05-13 08:20:35', "2013-01-15 09:09:09"]
#then create an array by
np.array(dates,dtype=np.datetime64)

Note: Having 5-6 elements inside list is not an ideal case(when comes to real data) so you have to use to_datetime() method in pandas as it is more flexible and efficient:

In addition to answer given by @atomh33ls:

After using to_datetime() method in pandas you can easily convert that back to numpy by using values attribute or to_numpy() method

a.values
#OR
a.to_numpy()

1 Comment

What do you mean by "efficient" when speaking about to_datetime?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.