【问题标题】:Why am I Getting Different results from timestamp (datetime.datetime vs. pandas.Series datetime64)?为什么我从时间戳(datetime.datetime 与 pandas.Series datetime64)得到不同的结果?
【发布时间】: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


【解决方案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

Difference between local and UTC datetimes 是测试 dt.fromtimestamp 时不同日期时间的原因。

【讨论】:

    【解决方案2】:

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

    要获得与 UTC 一致的时间,您应该使用utcfromtimestamp,如下所述:

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

    【讨论】:

      猜你喜欢
      • 2014-04-28
      • 2015-03-03
      • 1970-01-01
      • 2019-09-07
      • 1970-01-01
      • 1970-01-01
      • 2019-09-22
      • 1970-01-01
      相关资源
      最近更新 更多