Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python Pandas - Chuyển DateTimeIndex sang Series loại bỏ múi giờ

Để chuyển DateTimeIndex sang Series và loại bỏ múi giờ (timezone), sử dụng chuỗi phương thức tz_convert(None).to_series().

Các bước thực hiện

1. Import thư viện

import pandas as pd

2. Tạo DateTimeIndex có múi giờ

datetimeindex = pd.date_range(
    '2021-10-18 07:20:32.261811624',
    periods=5,
    tz='Australia/Adelaide',
    freq='40S'
)

3. Chuyển sang Series, loại bỏ timezone

print("\nDateTimeIndex to Series (không timezone)...\n",
      datetimeindex.tz_convert(None).to_series())

Ví dụ hoàn chỉnh

import pandas as pd

datetimeindex = pd.date_range(
    '2021-10-18 07:20:32.261811624',
    periods=5,
    tz='Australia/Adelaide',
    freq='40S'
)

print("DateTimeIndex...\n", datetimeindex)
print("DateTimeIndex frequency...\n", datetimeindex.freq)
print("\nDateTimeIndex to Series (không timezone)...\n",
      datetimeindex.tz_convert(None).to_series())

Kết quả đầu ra

DateTimeIndex...
DatetimeIndex(['2021-10-18 07:20:32.261811624+10:30', ...],
              dtype='datetime64[ns, Australia/Adelaide]', freq='40S')

DateTimeIndex to Series (không timezone)...
2021-10-17 20:50:32.261811624    2021-10-17 20:50:32.261811624
2021-10-17 20:51:12.261811624    2021-10-17 20:51:12.261811624
2021-10-17 20:51:52.261811624    2021-10-17 20:51:52.261811624
2021-10-17 20:52:32.261811624    2021-10-17 20:52:32.261811624
2021-10-17 20:53:12.261811624    2021-10-17 20:53:12.261811624
Freq: 40S, dtype: datetime64[ns]

Giải thích

  • tz_convert(None): Chuyển đổi sang UTC rồi loại bỏ thông tin timezone, trả về naive datetime (không múi giờ). Giá trị thời gian được điều chỉnh về UTC (ví dụ: +10:30 → -10:30 so với giờ địa phương).
  • to_series(): Chuyển Index thành Series, index của Series là chính các giá trị datetime.

Lưu ý: Nếu muốn giữ giờ địa phương nhưng bỏ timezone, dùng tz_localize(None) (chỉ gán nhãn, không chuyển đổi giờ).