解析时区并转换为夏令时 [英] parse time zone and convert to daylight saving time

查看:138
本文介绍了解析时区并转换为夏令时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 Datetime 列的熊猫数据框:

I have a pandas dataframe with a Datetime column:

         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不知道这一点)。我需要通过夏令时调整将日期时间转换为美国中部(芝加哥)。我该怎么做,即:

The datetimes are in Eastern Standard Time (EST) WITHOUT Daylight savings adjustments (python doesn't know this). I need to convert the datetimes to US Central (Chicago) WITH Daylight savings adjustments. How can I do this, i.e.:


  1. 告诉python日期时间在EST中且没有DST

  2. 将DST到CT的日期时间


推荐答案

回顾:您基本上拥有的日期时间对象是UTC-4 (EST),就不会过渡到EDT(UTC-5)。

Recap: you basically have datetime objects which are UTC-4 (EST), there is no transition to EDT (UTC-5).

因此,您可以通过添加4小时的timedelta将本地日期时间本地化为UTC,然后转换为CT:

What you could therefore do is localize from naive datetime to UTC by adding a timedelta of 4 hours and subsequently convert to 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

The example contains datetimes that would not exist with DST transition (2019-03-10 02:00:00). After the conversion to UTC to CT, DST transition is represented; 2019-03-10 01:00:00 -> 2019-03-10 03:00:00.

这篇关于解析时区并转换为夏令时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆