簡體   English   中英

如何使用 Python 將 UTC 轉換為 EST 並自動處理夏令時?

[英]How to convert UTC to EST with Python and take care of daylight saving automatically?

如果我有一堆UTC format的日期和時間數據,我如何將它們轉換為EST

它可以每年自動確定它們何時為-4(in summer)5(in winter) 謝謝

您需要使用pytz模塊(可從 PyPI 獲得):

import pytz
from datetime import datetime

est = pytz.timezone('US/Eastern')
utc = pytz.utc
fmt = '%Y-%m-%d %H:%M:%S %Z%z'

winter = datetime(2016, 1, 24, 18, 0, 0, tzinfo=utc)
summer = datetime(2016, 7, 24, 18, 0, 0, tzinfo=utc)

print winter.strftime(fmt)
print summer.strftime(fmt)

print winter.astimezone(est).strftime(fmt)
print summer.astimezone(est).strftime(fmt)

這將打印:

2016-01-24 18:00:00 UTC+0000
2016-07-24 18:00:00 UTC+0000
2016-01-24 13:00:00 EST-0500
2016-07-24 14:00:00 EDT-0400

您需要使用'US/Eastern'而不是'EST'原因在最后兩行輸出中舉例說明。

如果您有一個對象數據類型的Pandas系列,您可以先使用pd.to_datetime()將其轉換為 DateTime 系列

df[col] = pd.to_datetime(your_series, format = '%Y-%m-%d %H:%M:%S', errors ='coerce')

使用series.dt.tz檢查它是否知道時區

df[col].dt.tz

如果它不知道時區,我們應該使用series.dt.tz_localize()讓它知道時區。 另外,請閱讀此函數的不明確和不存在的參數

df[col] = your_series[col].dt.tz_localize('UTC')

現在通過series.dt.tz_convert()將此系列轉換為所需的時區

df[col] = your_series[col].dt.tz_convert('US/Eastern')

上述方法將處理夏令時。 如果您想檢查更多時區,您可以 pip install pytz 和

import pytz
pytz.common_timezones

如上所述,您可以像這樣使用pandas.DataFrame.tz_convert()

import pandas as pd
from datetime import datetime

df = pd.read_csv("your_data_file_path.csv", index_col=False, engine='python')
df['Date'] = pd.to_datetime(df['Date'])
df['Date'] = df['Date'].dt.tz_localize('US/Eastern').dt.tz_convert('UTC')
df['Date'] = df['Date'].apply(lambda x: datetime.replace(x, tzinfo=None))

最后一行的作用是從 datetime 對象中刪除時區信息,因此您只能使用日期和時間進行操作(不用擔心,這不會再次更改時區,它只是將其從時間戳字符串中刪除)。

如果您只想要現有 timedelta 偏移的標准化小時偏移:

from datetime import datetime
import pytz

def curr_est_offset():
    tz_est = pytz.timezone('US/Eastern')
    offset = tz_est.utcoffset(datetime.utcnow())
    offset_seconds = (offset.days * 86400) + offset.seconds
    offset_hours = offset_seconds // 3600

    return offset_hours # -4 or -5

這是 thebjorn 的答案,從 Python 2 轉換為Python 3並添加了一些評論。 感謝比約恩。

為了約定,我使用這些術語:

  • EST :東部標准時間(冬季)
  • EDT :東部夏令時間(夏季)
  • EPT :東部流行時間(標准或夏令時,視情況而定)

代碼

# Convert EPT / UTC

# Timezones
ept = pytz.timezone('US/Eastern')
utc = pytz.utc
# str format
fmt = '%Y-%m-%d %H:%M:%S %Z%z'

print("\nEPT/UTC examples:")
print("\nWinter (EST) example:")
# Create a UTC time in the winter
winter_utc = dtdt(2016, 1, 24, 18, 0, 0, tzinfo=utc)
print("    UTC: ", winter_utc.strftime(fmt))
# Convert from UTC to eastern prevailing time.  Since, the timestamp is in the
# winter, prevailing time is standard time.
winter_ept = winter_utc.astimezone(ept)
print("    EPT: ", winter_ept.strftime(fmt))
# Let's convert back to UTC to show we get back to the original value.
winter_utc2 = winter_ept.astimezone(utc)
print("    UTC: ", winter_utc2.strftime(fmt))

# Let's do that again for a summer datetime.
print("\nSummer (EDT) example:")
summer_utc = dtdt(2016, 7, 24, 18, 0, 0, tzinfo=utc)
print("    UTC: ", summer_utc.strftime(fmt))
# Convert from UTC to eastern prevailing time.  Since, the timestamp is in the
# winter, prevailing time is daylight saving time.
summer_ept = summer_utc.astimezone(ept)
print("    EPT: ", summer_ept.strftime(fmt))
# Let's convert back to UTC to show we get back to the original value.
summer_utc2 = summer_ept.astimezone(utc)
print("    UTC: ", summer_utc2.strftime(fmt))

控制台

 EPT/UTC examples: Winter (EST) example: UTC: 2016-01-24 18:00:00 UTC+0000 EPT: 2016-01-24 13:00:00 EST-0500 UTC: 2016-01-24 18:00:00 UTC+0000 Summer (EDT) example: UTC: 2016-07-24 18:00:00 UTC+0000 EPT: 2016-07-24 14:00:00 EDT-0400 UTC: 2016-07-24 18:00:00 UTC+0000

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM