Home >Backend Development >Python Tutorial >How to Convert Between `datetime`, `Timestamp`, and `datetime64` in Python?

How to Convert Between `datetime`, `Timestamp`, and `datetime64` in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-12-12 20:00:221031browse

How to Convert Between `datetime`, `Timestamp`, and `datetime64` in Python?

Converting Between datetime, Timestamp, and datetime64

Converting between different time representations is often necessary when working with data. One common scenario is converting between numpy.datetime64, datetime.datetime, and Timestamp objects.

numpy.datetime64 is a NumPy object representing a date and time with nanosecond precision. To convert a datetime.datetime or Timestamp object to a datetime64, you can use the np.datetime64() constructor.

datetime.datetime is a Python object representing a date and time with microsecond precision. To obtain a datetime.datetime from a datetime64 or Timestamp object, use the corresponding object's to_datetime() method.

Timestamp is a Pandas object representing a date and time with nanosecond precision. To create a Timestamp from a datetime.datetime or datetime64 object, you can use the pd.Timestamp() constructor.

As an example, consider the following objects:

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)

To convert these objects between different representations, you can use the following code:

# Convert datetime64 to datetime
datetime_from_dt64 = dt64.astype(datetime.datetime)

# Convert Timestamp to datetime
datetime_from_ts = ts.to_datetime()

# Convert datetime to Timestamp
timestamp_from_dt = pd.Timestamp(dt)

Remember that these conversions may result in a loss of precision due to the different time scales used by each representation.

The above is the detailed content of How to Convert Between `datetime`, `Timestamp`, and `datetime64` in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn