【发布时间】:2019-12-13 06:39:45
【问题描述】:
我有一个 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- 我想知道如何使用这两种方法获得相同的结果
【问题讨论】:
-
我相信它与时区有关。
Timestamp('2013-10-22 14:40:59')正在使用UTC时区。但是datetime.datetime(2013, 10, 22, 18, 10, 59)使用的是您所在地区的时区。
标签: python pandas dataframe datetime timestamp