如何使用 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))

最后一行所做的是从日期时间对象中删除时区信息,这样您就可以仅使用日期和时间进行操作(别担心,这不会再次更改时区,它只是将其从时间戳字符串)。

如果您只想为现有的 timedelta shifting 标准化小时偏移:

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 并添加了一些评论。感谢 thebjorn。

为了方便起见,我使用这些术语:

  • 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