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>
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>
Or use tz_convert(None) to remove the timezone and convert to UTC:
<code class="python">t.tz_convert(None)</code>
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>
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>
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')
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!