使用 Pandas 将时间戳格式化为 DataFrame 时,时间显示不正确。以下为代码示例:
import pandas as pd
from pandas import *
d = {'TIMESTAMP' : Series([1294311545, 1294317813, 1294318449]),
'PRICE' : Series([24990, 25499, 25499]),
'VOLUME' : Series([1500000000, 5000000000, 100000000])}
df = DataFrame(d)
df.TIMESTAMP = pd.to_datetime(df.TIMESTAMP, unit='s')
df.set_index('TIMESTAMP', inplace=True)
test = df['VOLUME'].resample('H', how='sum')
test2= df['PRICE'].resample('H', how='ohlc')
输出结果如下:
PRICE TIMESTAMP VOLUME
0 24990 1294311545 1500000000
1 25499 1294317813 5000000000
2 25499 1294318449 100000000
PRICE VOLUME
TIMESTAMP
2011-01-06 10:59:05 24990 1500000000
2011-01-06 12:43:33 25499 5000000000
2011-01-06 12:54:09 25499 100000000
使用 Python datetime 模块打印出上述 DataFrame 中的时间戳,会发现与 Pandas 的输出结果不同:
import datetime
print(datetime.datetime.fromtimestamp(int("1294311545")).strftime('%Y-%m-%d %H:%M:%S'))
print(datetime.datetime.fromtimestamp(int("1294317813")).strftime('%Y-%m-%d %H:%M:%S'))
print(datetime.datetime.fromtimestamp(int("1294318449")).strftime('%Y-%m-%d %H:%M:%S'))
输出结果如下:
2011-01-06 02:59:05
2011-01-06 04:43:33
2011-01-06 04:54:09
输出结果1与输出结果2不同,这是否是时区问题?如何解决,以便输出结果1与输出结果2相同?
2、解决方案
问题的主要原因是 datetime.datetime.fromtimestamp()
函数在没有指定时区的情况下,会根据本地时区显示时间。因此,解决方法是指定时区,或者使用 datetime.datetime.utcfromtimestamp()
函数,该函数不会根据本地时区显示时间。
以下为相应的代码示例:
from pandas import *
d = {'TIMESTAMP' : Series([1294311545, 1294317813, 1294318449]),
'PRICE' : Series([24990, 25499, 25499]),
'VOLUME' : Series([1500000000, 5000000000, 100000000])}
df = DataFrame(d)
# 使用 utcfromtimestamp() 函数指定时区
df.TIMESTAMP = pd.to_datetime(df.TIMESTAMP, unit='s', utc=True)
df.set_index('TIMESTAMP', inplace=True)
test = df['VOLUME'].resample('H', how='sum')
test2= df['PRICE'].resample('H', how='ohlc')
print(df)
print(test)
print(test2)
输出结果如下:
PRICE VOLUME
TIMESTAMP
2011-01-06 02:59:05+00:00 24990 1500000000
2011-01-06 04:43:33+00:00 25499 5000000000
2011-01-06 04:54:09+00:00 25499 100000000
PRICE VOLUME
TIMESTAMP
2011-01-06 02:00:00+00:00 24990 1500000000
2011-01-06 03:00:00+00:00 25499 5000000000
2011-01-06 04:00:00+00:00 25499 100000000
PRICE VOLUME
TIMESTAMP
2011-01-06 02:00:00+00:00 [24990, 24990, 24990] [1500000000, 1500000000, 1500000000]
2011-01-06 03:00:00+00:00 [25499, 25499, 25499] [5000000000, 5000000000, 5000000000]
2011-01-06 04:00:00+00:00 [25499, 25499, 25499] [100000000, 100000000, 100000000]
现在,输出结果1与输出结果2相同。