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

Python 为什么我从时间戳(datetime.datetime与pandas.Series datetime64)得到不同的结果?,python,pandas,dataframe,datetime,timestamp,Python,Pandas,Dataframe,Datetime,Timestamp,我有一个熊猫数据帧,包括一列时间戳,例如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

我有一个熊猫数据帧,包括一列时间戳,例如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-我想知道如何使用这两种方法获得相同的结果

我认为最好是在这里使用参数unit=s:

如果测试dt.fromtimestamp,则为不同日期时间的原因。

fromtimestamp以本地时间为单位提供时间戳,而数据帧上的aType'datetime64[s]'[0]默认以UTC为单位提供时间

要使时间在UTC中保持一致,应使用UTCFROM时间戳,如下所述:


打印dt.utcfromtimestamp1382452859.strftime“%Y-%m-%d%H:%m:%S”

我认为它与时区有关。时间戳“2013-10-22 14:40:59”使用UTC时区。但是datetime.datetime2013、10、22、18、10、59正在使用您的区域设置时区。
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