Converting between datetime, Timestamp and datetime64
When working with time representations in Python, it's common to encounter different data types such as datetime, Timestamp, and datetime64. Understanding how to convert between these types is essential for effective date and time operations.
Let's consider the snippet below, which creates instances of datetime, Timestamp, and datetime64:
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)
Obtaining the datetime from a Timestamp is straightforward using the to_datetime method:
ts.to_datetime()
However, extracting the datetime or Timestamp from a numpy.datetime64 (dt64) can be a bit tricky. To convert dt64 to a Timestamp, simply use the pd.Timestamp constructor:
pd.Timestamp(dt64)
This conversion process is made easier by referencing the following diagram:
[Image of a diagram showing conversions between datetime, Timestamp, and datetime64]
The above is the detailed content of How to Convert Between Python's `datetime`, `Timestamp`, and `datetime64`?. For more information, please follow other related articles on the PHP Chinese website!