为什么我从时间戳获取不同的结果(datetime.datetime与pandas.Series datetime64)?

时间:2019-12-13 06:39:45

标签: python pandas dataframe datetime timestamp

我有一个pandas DataFrame,其中包含一列时间戳(例如1382452859)。现在,我想将此列转换为普通的日期和时间(例如2013-10-22 18:10:59)。 我尝试了两种不同的方法,但是我不知道为什么会得到不同的答案:

# my DataFrame's head
df.head()
    Timestamp   Consumption
0   1382452859  12
1   1382452865  0
2   1382452871  12
3   1382452878  12
4   1382452884  12

#  getting the time of the first row using Pandas Series astype
df['Timestamp'].astype('datetime64[s]')[0]

output: Timestamp('2013-10-22 14:40:59') # which is 2013-10-22 14:40:59


# getting the time of the same row using datetime.datetime
dt.fromtimestamp(df.iloc[0]['Timestamp'])

output: datetime.datetime(2013, 10, 22, 18, 10, 59) # which is 2013-10-22 18:10:59

1-我想知道为什么这些方法给我带来不同的结果

2-我想知道哪种方法可以给我正确的结果

3-我想知道如何使用两种方法获得相同的结果

2 个答案:

答案 0 :(得分:1)

我认为最好将to_datetime与参数unit=s一起使用:

df['Timestamp'] = pd.to_datetime(df['Timestamp'], unit='s')
print (df)
            Timestamp  Consumption
0 2013-10-22 14:40:59           12
1 2013-10-22 14:41:05            0
2 2013-10-22 14:41:11           12
3 2013-10-22 14:41:18           12
4 2013-10-22 14:41:24           12
如果测试dt.fromtimestamp

Difference between local and UTC datetimes是日期时间不同的原因。

答案 1 :(得分:0)

fromtimestamp为您提供本地时间的时间戳记,而数据帧上的astype('datetime64[s]')[0]为您提供默认的UTC时间。

要使时间与UTC保持一致,应使用utcfromtimestamp,如下所述:

print (dt.utcfromtimestamp(1382452859).strftime('%Y-%m-%d %H:%M:%S'))