Python Pandas日期索引系列日期和时间转换为一个时区到另一个时区

时间:2019-04-02 11:34:54

标签: python-3.x pandas datetime time

从外部数据源接收并对齐以下数据。

                        open    high     low   close  volume
timestamp                                                  
2019-04-02 05:59:00  381.00  381.00  379.70  379.70       0
2019-04-02 05:58:00  380.90  380.90  380.85  380.85    5040
2019-04-02 05:57:00  380.85  380.95  380.65  380.95    9615
2019-04-02 05:56:00  380.60  381.20  380.60  381.00   13041
2019-04-02 05:55:00  379.80  380.60  379.80  380.60   19586
import pandas as pd
import sys
if sys.version_info[0] < 3: 
    from StringIO import StringIO
else:
    from io import StringIO

csvdata = StringIO("""timestamp,open,high,low,close,volume
2019-04-02 05:59:00,381.00,381.00,379.70,379.70,0
2019-04-02 05:58:00,380.90,380.90,380.85,380.85,5040
2019-04-02 05:57:00,380.85,380.95,380.65,380.95,9615
2019-04-02 05:56:00,380.60,381.20,380.60,381.00,13041
2019-04-02 05:55:00,379.80,380.60,379.80,380.60,19586""")

df = pd.read_csv(csvdata, sep=",", index_col="timestamp", parse_dates=True, infer_datetime_format=True)

# results
print( df)

此代码对于其他计算工作正常,但是此处显示的时间戳为GMT-4时间戳(需要从数据提供者那里了解)。 我希望将其从一个时区转换为另一个时区GMT-4到GMT + 5.30。 尝试了一些选项,但显示“日期”不是索引的一部分失败。如何将其作为可重用代码,就像从任何时区(输入时区可能更改为UTC或GMT-2)转换为所需时区一样。

#fmt = "%d-%m-%Y %H:%M:%S %Z%z"
#now.strftime('%m-%d-%y %H:%M:%S')
#x.strftime("%Y-%m-%dT%H:%M:%S%Z") #'2015-03-26T10:58:51'
fmt = "%d-%m-%Y %H:%M"
#keyupdate=key
dfdaily = pd.read_csv(dailyurl, index_col=[0], parse_dates=[0])
#dfdaily['date'] = pd.to_datetime(dfdaily['date'])
print(dfdaily.head(5))
dfdaily = dfdaily.rename_axis('date')
dfdaily= dfdaily.sort_index()
dfdaily.index.name = 'date'
print("Actual Time",dfdaily.index.strftime(fmt))
# Convert to US/Pacific time zone
now_pacific = dfdaily.index.astimezone(timezone('US/Pacific'))
print("Coverted US time",now_pacific['date'].strftime(fmt))
# Convert to Europe/Berlin time zone
now_india = now_pacific.index.astimezone(timezone('Asia/Kolkata'))
print("India Time",now_india['date'].strftime(fmt))
return dfdaily

**注意:**当我调试并看到检索到的数据时,它显示为2019-04-02T0205:59:00.0000,但是当我打印时为2019-04-02 05:59:00为什么?  打印(dfdaily.head(5))

在上面的代码中,我应该做些什么更改才能转换时区。同样对我来说,日期索引不起作用的原因也不知道为什么。

1 个答案:

答案 0 :(得分:1)

这里的窍门是输入数据。根据某些情况,日期时间数据将以“天真”(即IE no tz)或“ tz感知”的形式加载。给定以上代码中的MCVE,可以预期数据会“天真”加载。通过查看最初加载的索引进行检查。

df.index.tz

一旦使用DateTimeIndex构建数据帧,熊猫便可以完成所需的tz工作。

在以下答案中,请注意,Olson TZ数据库用于GMT + X小时偏移量中的地名。在这里,格林尼治标准时间+5:30是亚洲/加尔各答。

此外,对于时区和日期时间类型的任何高级操作,实际上都需要pytz库。

import pandas as pd
import sys
if sys.version_info[0] < 3:
    from StringIO import StringIO
else:
    from io import StringIO

csvdata = StringIO("""timestamp,open,high,low,close,volume
2019-04-02 05:59:00,381.00,381.00,379.70,379.70,0
2019-04-02 05:58:00,380.90,380.90,380.85,380.85,5040
2019-04-02 05:57:00,380.85,380.95,380.65,380.95,9615
2019-04-02 05:56:00,380.60,381.20,380.60,381.00,13041
2019-04-02 05:55:00,379.80,380.60,379.80,380.60,19586""")

df = pd.read_csv(csvdata, sep=",", index_col="timestamp", parse_dates=True, infer_datetime_format=True)

print("index type {}".format(type(df.index)))
# is tz 'naive'
print("index tz None is naive {}".format(df.index.tz))

# results
print(df)

# so give it a locale, since input data is naive, 
# UTC must be presumed unless there is additional
# input data not specified in above example
df.index = df.index.tz_localize("Etc/UTC")
# is tz 'naive'
print("index tz None is naive {}".format(df.index.tz))

# now that the DateTimeIndex has a tz, it may
# be converted as desired
random_tz = "Asia/Kolkata"
df.index = df.index.tz_convert("Asia/Kolkata")

# results
print(df)

index type <class 'pandas.core.indexes.datetimes.DatetimeIndex'>
index tz None is naive None
                       open    high     low   close  volume
timestamp                                                  
2019-04-02 05:59:00  381.00  381.00  379.70  379.70       0
2019-04-02 05:58:00  380.90  380.90  380.85  380.85    5040
2019-04-02 05:57:00  380.85  380.95  380.65  380.95    9615
2019-04-02 05:56:00  380.60  381.20  380.60  381.00   13041
2019-04-02 05:55:00  379.80  380.60  379.80  380.60   19586
index tz None is naive Etc/UTC
                             open    high     low   close  volume
timestamp                                                        
2019-04-02 11:29:00+05:30  381.00  381.00  379.70  379.70       0
2019-04-02 11:28:00+05:30  380.90  380.90  380.85  380.85    5040
2019-04-02 11:27:00+05:30  380.85  380.95  380.65  380.95    9615
2019-04-02 11:26:00+05:30  380.60  381.20  380.60  381.00   13041
2019-04-02 11:25:00+05:30  379.80  380.60  379.80  380.60   19586

请接受,这样可以回答问题。

相关问题