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

How to Convert a Timezone-Aware Timestamp to Naive Local Time in Pandas?

Mary-Kate Olsen
Release: 2024-11-05 02:05:01
Original
330 people have browsed it

How to Convert a Timezone-Aware Timestamp to Naive Local Time in Pandas?

How to Convert a Timezone-Aware Timestamp to Naive Local Time in Pandas

In pandas, the tz_localize function is used to create a timestamp or DateTimeIndex that is timezone-aware. However, when dealing with data that is already timezone-aware, there may be a need to convert it back to a naive timestamp while preserving the timezone information for local time.

One option is to set the timezone to None, but this results in the time being converted to UTC. To avoid this, pandas provides the tz_localize(None) function, which effectively removes the timezone information while preserving the user-visible time in the local timezone.

For example, consider the following timezone-aware DateTimeIndex:

t = pd.date_range(start="2013-05-18 12:00:00", periods=2, freq='H', tz="Europe/Brussels")
Copy after login

Using tz_localize(None), we can convert it to a naive local time:

t_naive_local = t.tz_localize(None)
Copy after login

The resulting index will have the same times as before, but without the timezone information:

t_naive_local

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

Additionally, pandas also provides the tz_convert(None) function, which removes the timezone information and converts the time to UTC, resulting in naive UTC time.

This conversion is significantly more efficient than the alternative approach of using the datetime.replace method, as demonstrated by the following timings:

%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
Copy after login

By leveraging these functions, it is easy to convert timezone-aware pandas data to naive local time or UTC, preserving the user-visible time and enhancing the efficiency of data handling.

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