【发布时间】:2018-07-03 03:30:14
【问题描述】:
如果我在UTC format 中有一堆包含日期和时间的数据,如何将它们转换为EST。
它可以每年自动确定它们何时是-4(in summer)和-5(in winter)?
谢谢
【问题讨论】:
标签: python datetime datetime-format python-datetime
如果我在UTC format 中有一堆包含日期和时间的数据,如何将它们转换为EST。
它可以每年自动确定它们何时是-4(in summer)和-5(in winter)?
谢谢
【问题讨论】:
标签: python datetime datetime-format python-datetime
您需要使用 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 对象中删除时区信息,因此您可以仅使用日期和时间进行操作(不用担心,这不会再次更改时区,它只是将其从时间戳中剥离字符串)。
【讨论】:
如果您只想要现有时间增量偏移的标准化小时偏移量:
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 并添加了一些额外的 cmets。感谢 thebjorn。
为了约定,我使用这些术语:
代码:
# 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
【讨论】: