When working with timestamps and dates in Python, it's often necessary to convert between different data types. This includes converting between numpy.datetime64, datetime.datetime, and datetime64 objects.
To convert a numpy.datetime64 object dt64 to a datetime.datetime object dt, simply use dt = dt64.astype(datetime.datetime). Note that the timezone information may not be preserved in this conversion.
Similarly, to convert dt64 to a datetime.Timestamp object ts, use ts = pd.Timestamp(dt64). This will ensure that the timezone information is maintained.
To convert a datetime.datetime object dt to a numpy.datetime64 object dt64, use dt64 = np.datetime64(dt). This will create a datetime64 object with the same timestamp as dt.
To convert a datetime.Timestamp object ts to a numpy.datetime64 object dt64, use dt64 = ts.timestamp().astype(np.datetime64). This will create a datetime64 object with the same timestamp and timezone as ts.
Consider the following example:
import datetime import numpy as np import pandas as pd dt = datetime.datetime(2012, 5, 1) ts = pd.DatetimeIndex([dt])[0] dt64 = np.datetime64(dt) print(dt64.astype(datetime.datetime)) print(pd.Timestamp(dt64))
This will output:
2012-05-01 00:00:00 <Timestamp: 2012-05-01 00:00:00+00:00>
Note that the timezone information was preserved when converting from dt64 to Timestamp, but lost when converting to datetime.datetime.
The above is the detailed content of How to Convert Between NumPy Datetime64, Datetime, and Timestamp Objects?. For more information, please follow other related articles on the PHP Chinese website!