Home >Backend Development >Python Tutorial >How Can I Convert Between Python's `datetime`, `Timestamp`, and `datetime64`?

How Can I Convert Between Python's `datetime`, `Timestamp`, and `datetime64`?

DDD
DDDOriginal
2024-12-04 20:24:17564browse

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!

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