Home >Backend Development >Python Tutorial >How Can I Convert Between Python's `datetime`, `Timestamp`, and `datetime64`?
Converting between datetime, Timestamp and datetime64
Working with different time representations in Python can be a challenge. NumPy's datetime64, pandas' Timestamp, and datetime's datetime objects each have their own advantages and disadvantages. Here's how to convert between them:
datetime.datetime to Timestamp
Simply use the pd.Timestamp constructor:
import pandas as pd dt = datetime.datetime(2012, 5, 1) ts = pd.Timestamp(dt)
datetime64 to datetime.datetime
Again, use the pd.Timestamp constructor:
import numpy as np import pandas as pd dt64 = np.datetime64('2002-06-28T01:00:00.000000000+0100') dt = pd.Timestamp(dt64).to_datetime()
Reference Diagram
For a visual representation of these conversions, refer to the following diagram:
[Image of conversions between time representations]
The above is the detailed content of How Can I Convert Between Python's `datetime`, `Timestamp`, and `datetime64`?. For more information, please follow other related articles on the PHP Chinese website!