How to convert numpy datetime64 [ns] to python datetime?

2024/10/2 20:33:05

I need to convert dates from pandas frame values in the separate function:

 def myfunc(lat, lon, when):ts = (when - np.datetime64('1970-01-01T00:00:00Z','s')) / np.timedelta64(1, 's')date = datetime.datetime.utcfromtimestamp(ts)print("Numpy date= ", when, " Python date= ", date)return float(90) - next_func(lat, lon, date)

Invokation this function:

new_df['new_column'] =  np.vectorize(my_func)(lat, lon, new_df['datetime(LT)'])  

But it raise error:

ufunc subtract cannot use operands with types dtype('int64') and dtype('<M8[s]')

How to convert numpy datetime64 [ns] to python datetime?

Answer

I wonder if you need all this conversion work. With the right time units a datetime64 can produce a datetime object directly.

I'm not sure about your when variable, but let's assume it comes from pandas, and is something like a DatetimeIndex:

In [56]: time = pandas.date_range('6/28/2013', periods=5, freq='5D')
In [57]: time
Out[57]: 
DatetimeIndex(['2013-06-28', '2013-07-03', '2013-07-08', '2013-07-13','2013-07-18'],dtype='datetime64[ns]', freq='5D')

The equivalent numpy array

In [58]: time.values
Out[58]: 
array(['2013-06-28T00:00:00.000000000', '2013-07-03T00:00:00.000000000','2013-07-08T00:00:00.000000000', '2013-07-13T00:00:00.000000000','2013-07-18T00:00:00.000000000'], dtype='datetime64[ns]')
In [59]: time.values.tolist()
Out[59]: 
[1372377600000000000,1372809600000000000,1373241600000000000,1373673600000000000,1374105600000000000]

With [ns] the result is a large integer, a 'timestamp' of some sort. But if I convert the time units to something like seconds, or even microseconds (us):

In [60]: time.values.astype('datetime64[s]')
Out[60]: 
array(['2013-06-28T00:00:00', '2013-07-03T00:00:00','2013-07-08T00:00:00', '2013-07-13T00:00:00','2013-07-18T00:00:00'], dtype='datetime64[s]')
In [61]: time.values.astype('datetime64[s]').tolist()
Out[61]: 
[datetime.datetime(2013, 6, 28, 0, 0),datetime.datetime(2013, 7, 3, 0, 0),datetime.datetime(2013, 7, 8, 0, 0),datetime.datetime(2013, 7, 13, 0, 0),datetime.datetime(2013, 7, 18, 0, 0)]

the result is a list of datetime objects.

https://en.xdnf.cn/q/70814.html

Related Q&A

how to remove a back slash from a JSON file

I want to create a json file like this:{"946705035":4,"946706692":4 ...}I am taking a column that only contains Unix Timestamp and group them.result = data[Last_Modified_Date_unixti…

Can sockets be used to connect multiple computers on different networks in python? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 6…

python logging close and application exit

I am using the logging module in an application and it occurred to me that it would be neat if the logging module supported a method which would gracefully close file handles etc and then close the app…

LookupError: unknown encoding: cp0

I am on window 7, python 2.7.2, pandas 0.11.0, django 1.4, wsgi and apache 2.2. I have a pandas script that works fine if I run it directly with python and also works in ipython with %run. However, w…

Cant activate Python venv in Windows 10

I created a virtual environment with python -m venv myenv from the command prompt, but I dont know how to activate it. I tried executing activate.bat from the command prompt but it does not activate.In…

Opening file path not working in python [duplicate]

This question already has answers here:open() gives FileNotFoundError / IOError: [Errno 2] No such file or directory(11 answers)Closed last year.I am writing a database program and personica is my test…

Cython: Segmentation Fault Using API Embedding Cython to C

Im trying to embed Cython code into C following Oreilly Cython book chapter 8. I found this paragraph on Cythons documentation but still dont know what should I do:If the C code wanting to use these fu…

Computing AUC and ROC curve from multi-class data in scikit-learn (sklearn)?

I am trying to use the scikit-learn module to compute AUC and plot ROC curves for the output of three different classifiers to compare their performance. I am very new to this topic, and I am struggli…

Nested dictionary

I am working on some FASTA-like sequences (not FASTA, but something I have defined thats similar for some culled PDB from the PISCES server).I have a question. I have a small no of sequences called nCa…

How to create a Python script to automate software installation? [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…