[英]parse time zone and convert to daylight saving time
我有一个带有Datetime
列的 pandas dataframe:
Datetime
0 2019-01-01 17:02:00
1 2019-01-01 17:03:00
2 2019-01-01 17:04:00
3 2019-01-01 17:05:00
...
日期时间采用东部标准时间 (EST),没有夏令时调整(python 不知道这一点)。 我需要通过夏令时调整将日期时间转换为美国中部(芝加哥)。 我该怎么做,即:
您可以首先使用tz_localize
使其具有时区意识,然后转换为中央时区。 然后您可以使用dst
检查是否是夏令时。 我也添加了以后的日期。 一旦你知道它是否是 dst,你可以从中增加或减少 1 小时:
df['Datetime'] = pd.to_datetime(df['Datetime'])
df['New_Datetime'] = df['Datetime'].dt.tz_localize('US/Eastern').dt.tz_convert('US/Central')
df['is_dst'] = df['New_Datetime'].map(lambda x : int(x.dst().total_seconds()!=0))
print(df)
Datetime New_Datetime is_dst
0 2019-01-01 17:02:00 2019-01-01 16:02:00-06:00 0
1 2019-01-01 17:03:00 2019-01-01 16:03:00-06:00 0
2 2019-01-01 17:04:00 2019-01-01 16:04:00-06:00 0
3 2019-01-01 17:05:00 2019-01-01 16:05:00-06:00 0
4 2019-06-06 17:05:00 2019-06-06 16:05:00-05:00 1
回顾:您基本上拥有 UTC-4 (EST) 的日期时间对象,没有过渡到 EDT (UTC-5)。
因此,您可以做的是通过添加 4 小时的 timedelta 将原始日期时间本地化为 UTC,然后转换为 CT:
import pandas as pd
# df with naive datetime objects that represent US/Eastern without DST
df = pd.DataFrame({'DateTime': pd.to_datetime(['2019-03-10 02:00:00',
'2019-03-10 03:00:00',
'2019-03-10 04:00:00'])})
# to UTC; EST is 4 hours behind UTC
df['DateTime_UTC'] = df['DateTime'].dt.tz_localize('UTC') + pd.Timedelta(hours=4)
# now convert from UTC to US/Central, UTC-6 with DST, -5 w/o DST
df['DateTime_CT'] = df['DateTime_UTC'].dt.tz_convert('US/Central')
# df['DateTime_CT']
# 0 2019-03-10 00:00:00-06:00
# 1 2019-03-10 01:00:00-06:00
# 2 2019-03-10 03:00:00-05:00
# Name: DateTime_CT, dtype: datetime64[ns, US/Central]
该示例包含 DST 转换 ( 2019-03-10 02:00:00
) 不存在的日期时间。 UTC转CT后,表示DST过渡; 2019-03-10 01:00:00
-> 2019-03-10 03:00:00
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.