Home > Backend Development > Python Tutorial > How to Convert Between NumPy Datetime64, Datetime, and Timestamp Objects?

How to Convert Between NumPy Datetime64, Datetime, and Timestamp Objects?

Linda Hamilton
Release: 2024-12-14 19:28:11
Original
472 people have browsed it

How to Convert Between NumPy Datetime64, Datetime, and Timestamp Objects?

Converting Between Numpy Datetime64, Datetime and Timestamp Objects

When working with timestamps and dates in Python, it's often necessary to convert between different data types. This includes converting between numpy.datetime64, datetime.datetime, and datetime64 objects.

Converting from Datetime64 to Datetime or Timestamp

To convert a numpy.datetime64 object dt64 to a datetime.datetime object dt, simply use dt = dt64.astype(datetime.datetime). Note that the timezone information may not be preserved in this conversion.

Similarly, to convert dt64 to a datetime.Timestamp object ts, use ts = pd.Timestamp(dt64). This will ensure that the timezone information is maintained.

Converting from Datetime or Timestamp to Datetime64

To convert a datetime.datetime object dt to a numpy.datetime64 object dt64, use dt64 = np.datetime64(dt). This will create a datetime64 object with the same timestamp as dt.

To convert a datetime.Timestamp object ts to a numpy.datetime64 object dt64, use dt64 = ts.timestamp().astype(np.datetime64). This will create a datetime64 object with the same timestamp and timezone as ts.

Example Conversion

Consider the following example:

import datetime
import numpy as np
import pandas as pd

dt = datetime.datetime(2012, 5, 1)
ts = pd.DatetimeIndex([dt])[0]
dt64 = np.datetime64(dt)

print(dt64.astype(datetime.datetime))
print(pd.Timestamp(dt64))
Copy after login

This will output:

2012-05-01 00:00:00
<Timestamp: 2012-05-01 00:00:00+00:00>
Copy after login

Note that the timezone information was preserved when converting from dt64 to Timestamp, but lost when converting to datetime.datetime.

The above is the detailed content of How to Convert Between NumPy Datetime64, Datetime, and Timestamp Objects?. 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