Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

How do I convert a numpy.datetime64 object to a datetime.datetime (or Timestamp)?

In the following code, I create a datetime, timestamp and datetime64 objects.

import datetime 

import numpy as np 

import pandas as pd 

dt = datetime.datetime(2012, 5, 1) 

# A strange way to extract a Timestamp object, there's surely a better way? 

ts = pd.DatetimeIndex([dt])[0] 

dt64 = np.datetime64(dt) 

In [7]: dt 

Out[7]: datetime.datetime(2012, 5, 1, 0, 0) 

In [8]: ts 

Out[8]: <Timestamp: 2012-05-01 00:00:00> 

In [9]: dt64 

Out[9]: numpy.datetime64('2012-05-01T01:00:00.000000+0100')

Note: it's easy to get the datetime from the Timestamp:

In [10]: ts.to_datetime() 

Out[10]: datetime.datetime(2012, 5, 1, 0, 0)

But how do we extract the datetime or Timestamp from a numpy.datetime64 (dt64)?

Update: a somewhat nasty example in my dataset (perhaps the motivating example) seems to be:

dt64 = numpy.datetime64('2002-06-28T01:00:00.000000000+0100')

which should be datetime.datetime(2002, 6, 28, 1, 0), and not a long (!) (1025222400000000000L)...

1 Answer

0 votes
by (106k points)

To convert between datetime, timestamp and datetime64 you can use the below-mentioned code:- 

>>> from datetime import datetime 

>>> import numpy as np 

>>> dt = datetime.utcnow() 

>>> dt 

datetime.datetime(2012, 12, 4, 19, 51, 25, 362455) 

>>> dt64 = np.datetime64(dt) 

>>> ts = (dt64 - np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(1, 's') 

>>> ts 

1354650685.3624549 

>>> datetime.utcfromtimestamp(ts) 

datetime.datetime(2012, 12, 4, 19, 51, 25, 362455) 

>>> np.__version__ 

'1.8.0.dev-7b75899'

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...