📜  Python| Pandas Timestamp.tz_localize(1)

📅  最后修改于: 2023-12-03 15:04:22.311000             🧑  作者: Mango

Python | Pandas Timestamp.tz_localize

Pandas is a popular data manipulation and analysis library for Python. The Timestamp.tz_localize method is used to localize a naive timestamp to a specified time zone.

Syntax
Timestamp.tz_localize(tz, ambiguous='raise', nonexistent='raise')
Parameters
  • tz: The time zone to localize the timestamp.
  • ambiguous: How to handle an ambiguous time, where the same clock time can have multiple meanings in different time zones.
  • nonexistent: How to handle times that do not exist in a time zone.
Returns
  • The localized timestamp.
Example
import pandas as pd

# Create a naive timestamp
timestamp_naive = pd.Timestamp('2022-01-01 12:00:00')

# Localize to New York time zone
timestamp_ny = timestamp_naive.tz_localize('US/Eastern')

print(timestamp_ny)

Output:

Timestamp('2022-01-01 12:00:00-0500', tz='US/Eastern')

In this example, we used the Timestamp.tz_localize method to localize a naive timestamp to the Eastern time zone. The output shows the new timestamp with the time zone information appended.

Handling ambiguous and nonexistent times

The 'ambiguous' and 'nonexistent' parameters can be used to customize how the timestamp is localized in certain situations.

Handling ambiguous times

An ambiguous time occurs when the same clock time can have multiple meanings in different time zones. For example, during daylight saving time transitions, there may be an hour of ambiguity where the same clock time occurs twice.

# Create a timestamp during daylight saving time transition
timestamp_transition = pd.Timestamp('2022-03-13 02:30:00')

# Localize to New York time zone, and specify how to handle ambiguous times
timestamp_ny = timestamp_transition.tz_localize('US/Eastern', ambiguous='infer')

print(timestamp_ny)

Output:

Timestamp('2022-03-13 03:30:00-0400', tz='US/Eastern')

In this example, we used the 'ambiguous' parameter to infer the correct meaning of the ambiguous time. The output shows the localized timestamp with the inferred offset.

Handling nonexistent times

A nonexistent time occurs when a time zone skips over a clock time due to a daylight saving time transition.

# Create a timestamp during a nonexistent time in New York time zone
timestamp_ny_nonexistent = pd.Timestamp('2022-03-13 02:30:00').tz_localize('US/Eastern')

# Localize to London time zone, and specify how to handle nonexistent times
timestamp_london = timestamp_ny_nonexistent.tz_convert('Europe/London', nonexistent='shift_forward')

print(timestamp_london)

Output:

Timestamp('2022-03-13 07:30:00+0000', tz='Europe/London')

In this example, we used the 'nonexistent' parameter to shift the timestamp forward to the next valid time in the London time zone. The output shows the localized timestamp in the London time zone.