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

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

Susan Sarandon
Release: 2024-12-05 08:16:11
Original
542 people have browsed it

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

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)
Copy after login

Obtaining the datetime from a Timestamp is straightforward using the to_datetime method:

ts.to_datetime()
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template