Home > Article > Backend Development > How to Convert Timezone-Aware Pandas DateTimeIndex to Naive Timestamps While Preserving Timezone?
Pandas provides the tz_localize function for adding timezone information to timestamps and datetime indices. However, the question here pertains to the reverse operation: converting timezone-aware timestamps to naive ones while maintaining the original timezone.
Starting with Pandas 0.15.0, the tz_localize(None) method has been implemented to facilitate this conversion. When applied to a timezone-aware DateTimeIndex, it removes the timezone information, resulting in naive local time.
import pandas as pd t = pd.date_range(start="2013-05-18 12:00:00", periods=2, freq='H', tz="Europe/Brussels") t_naive = t.tz_localize(None) # Naive local time print(t_naive) # Output: # DatetimeIndex(['2013-05-18 12:00:00', '2013-05-18 13:00:00'], dtype='datetime64[ns]', freq='H')
In addition to local time, you can also convert to naive UTC time using the tz_convert(None) method.
t_utc_naive = t.tz_convert(None) # Naive UTC time print(t_utc_naive) # Output: # DatetimeIndex(['2013-05-18 10:00:00', '2013-05-18 11:00:00'], dtype='datetime64[ns]', freq='H')
The tz_localize(None) method is highly efficient compared to using the datetime.replace solution. For a large DateTimeIndex, the performance gain can be significant.
The above is the detailed content of How to Convert Timezone-Aware Pandas DateTimeIndex to Naive Timestamps While Preserving Timezone?. For more information, please follow other related articles on the PHP Chinese website!