Home > Backend Development > Python Tutorial > How to Convert a Pandas Timezone-Aware DateTimeIndex to a Naive Timestamp in a Specific Timezone?

How to Convert a Pandas Timezone-Aware DateTimeIndex to a Naive Timestamp in a Specific Timezone?

Mary-Kate Olsen
Release: 2024-11-04 12:18:30
Original
971 people have browsed it

How to Convert a Pandas Timezone-Aware DateTimeIndex to a Naive Timestamp in a Specific Timezone?

Convert Pandas Timezone-Aware DateTimeIndex to Naive Timestamp in Specified Timezone

Pandas offers the tz_localize function to create a timezone-aware Timestamp or DateTimeIndex. But what if you want to undo this operation? How do you convert a timezone-aware Timestamp to a naive one without altering its timezone?

Problem:

Let's consider a timezone-aware DateTimeIndex:

<code class="python">t = pd.date_range(start="2013-05-18 12:00:00", periods=10, freq='s', tz="Europe/Brussels")</code>
Copy after login

Setting the timezone to None removes the timezone but converts the timestamps to UTC, altering the visible time.

Solution (Pandas 0.15.0 ):

Since Pandas 0.15.0, the tz_localize method can be used to set the timezone to None. This removes the timezone information while preserving the local time:

<code class="python">t.tz_localize(None)</code>
Copy after login

This results in a naive local time DateTimeIndex.

Alternatively, tz_convert(None) can be used to convert to naive UTC time:

<code class="python">t.tz_convert(None)</code>
Copy after login

Performance Considerations:

The tz_localize(None) method is significantly more efficient than using a loop to replace the timezone information:

<code class="python">%timeit t.tz_localize(None)
1000 loops, best of 3: 233 µs per loop

%timeit pd.DatetimeIndex([i.replace(tzinfo=None) for i in t])
10 loops, best of 3: 99.7 ms per loop</code>
Copy after login

The above is the detailed content of How to Convert a Pandas Timezone-Aware DateTimeIndex to a Naive Timestamp in a Specific Timezone?. 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