Python将夏令时转换为标准时区时间 [英] Python Convert Daylight Saving time to Standard Zone time

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

问题描述

我有来自字段(佛罗里达)的数据,这将其保存为本地时间。佛罗里达州有夏令时。因此,我想将其转换为EST区域。我该怎么做?
我的代码:

I have data coming from field (Florida), which saves it in local time. Florida has day light saving time. So, I want to convert this to EST zone. How do I do it? My code:

local_df.index = DatetimeIndex(['2019-06-01 06:58:45', '2019-10-01 06:59:00',
               '2019-10-01 06:59:15', 
               '2020-07-18 09:16:30', '2020-07-18 09:16:45'],
              dtype='datetime64[ns]', name='', freq=None)
est_df.index = local_df.index.tz_localize(tz='EST')
est_df.index = DatetimeIndex(['2019-06-01 06:58:45-05:00', '2019-10-01 06:59:00-05:00',
               '2019-10-01 06:59:15-05:00','2020-07-18 09:16:30-05:00', '2020-07-18 09:16:45-05:00'],
              dtype='datetime64[ns]', name='', freq=None)

我的上面代码实际上并未将本地时间转换为东部标准时间,而是仅将时差与UCT相加。这是不正确的。

My above code is actually not converting local time to the eastern standard time, it appends only the time difference with UCT. This is not correct.

推荐答案

请注意, EST 不是时间时区,但在一年中的特定时间偏离UTC某个时区。我建议使用 IANA时区名称来代替明确的地理归属。旁注:佛罗里达州有两个时区;美国/东部和美国/中部。

Note that EST is not a time zone but an offset from UTC of certain time zone(s) at a certain time of the year. I suggest to use IANA time zone names instead for an unambiguous geographical attribution. Side note: Florida has two time zones; US/Eastern and US/Central.

此外,要转换 UTC时间为时区时间,您必须先本地化为UTC。您的代码可能类似于

Furthermore, to convert UTC time to a time zone's time, you'll have to localize to UTC first. Your code could look something like

import pandas as pd

dti = pd.DatetimeIndex(['2019-06-01 06:58:45', '2019-10-01 06:59:00', '2019-10-01 06:59:15', 
                        '2020-07-18 09:16:30', '2020-07-18 09:16:45'])

dti_UTC = dti.tz_localize('UTC')
dti_USEastern = dti_UTC.tz_convert('US/Eastern')

# dti_USEastern
# DatetimeIndex(['2019-06-01 02:58:45-04:00', '2019-10-01 02:59:00-04:00',
#                '2019-10-01 02:59:15-04:00', '2020-07-18 05:16:30-04:00',
#                '2020-07-18 05:16:45-04:00'],
#               dtype='datetime64[ns, US/Eastern]', freq=None)

但是,如果输入类似于当地时间,例如美国/东部,您可以直接本地化到该时区:

If, however, the input resembles local time, say US/Eastern, you can directly localize to that time zone:

dti_USEastern = dti.tz_localize('US/Eastern')

# dti_USEastern
# DatetimeIndex(['2019-06-01 06:58:45-04:00', '2019-10-01 06:59:00-04:00',
#                '2019-10-01 06:59:15-04:00', '2020-07-18 09:16:30-04:00',
#                '2020-07-18 09:16:45-04:00'],
#               dtype='datetime64[ns, US/Eastern]', freq=None)

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

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