Home > Backend Development > Python Tutorial > How to Convert a Timezone-Aware Pandas DateTimeIndex to Naive Timestamps Without Changing the Timezone?

How to Convert a Timezone-Aware Pandas DateTimeIndex to Naive Timestamps Without Changing the Timezone?

Barbara Streisand
Release: 2024-11-04 13:04:30
Original
1108 people have browsed it

How to Convert a Timezone-Aware Pandas DateTimeIndex to Naive Timestamps Without Changing the Timezone?

How to Convert Pandasonic Timezone-Aware DateTimeIndex to Naive Timestamps While Preserving Timezone

Problem:

How can you convert a timezone-aware pandas Timestamp or DateTimeIndex to a naive one without modifying its timezone?

Original Code:

Using tz = None removes the timezone but also converts the time to UTC:

<code class="python">t.tz = None</code>
Copy after login

Suggested Solution:

  • From pandas 0.15.0 onward:

    Use tz_localize(None) to remove the timezone, resulting in naive local time:

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

    Or use tz_convert(None) to remove the timezone and convert to UTC:

    <code class="python">t.tz_convert(None)</code>
    Copy after login
  • Pre-pandas 0.15.0:

    Manually replace the timezone information with None using a list comprehension. However, this method is less efficient than the built-in methods.

    <code class="python">pd.DatetimeIndex([i.replace(tzinfo=None) for i in t])</code>
    Copy after login

Example:

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

# Using 'tz_localize(None)'
t_naive_local = t.tz_localize(None)

# Using 'tz_convert(None)'
t_naive_utc = t.tz_convert(None)

print(t_naive_local)
print(t_naive_utc)</code>
Copy after login

Output:

DatetimeIndex(['2013-05-18 12:00:00', '2013-05-18 13:00:00'], dtype='datetime64[ns]', freq='H')
DatetimeIndex(['2013-05-18 10:00:00', '2013-05-18 11:00:00'], dtype='datetime64[ns]', freq='H')
Copy after login

The above is the detailed content of How to Convert a Timezone-Aware Pandas DateTimeIndex to Naive Timestamps Without Changing the 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