如何将 Pandas 数据帧中的异常时间戳转换为日期时间

How to Convert Abnormal Timestamp into datetime in Pandas dataframe

我正在为某些用户分析创建使用热图。 Y 轴将是星期几,X 轴将是一天中的小时 (24:00)。我从API中提取了数据。(注意,这实际上产生了6,000行数据)

输入:

import requests
import json

response = requests.get("api.url")
data = response.json()
df=pd.DataFrame(data['Sessions'])
df.dtypes
print(df['StartTime'])

输出:

0     2019-01-29T22:08:40
1     2019-01-29T22:08:02
2     2019-01-29T22:05:10
3     2019-01-29T21:34:30
4     2019-01-29T21:32:49
Name: StartTime, Length: 100, dtype: object

我通常会将对象转换为 pandas.dt,然后将其分成两列:

输入:

df['StartTime'] =  pd.to_datetime(df['StartTime'], format='%d%b%Y:%H:%M:%S.%f')
df['Date'] = [d.date() for d in df['StartTime']]
df['Time'] = [d.time() for d in df['StartTime']]

输出:

'     StartTime                Date           Time
0     2019-01-29T22:08:40      2019-01-29     22:08:40
1     2019-01-29T22:08:02      2019-01-29     22:08:02
2     2019-01-29T22:05:10      2019-01-29     22:05:10
3     2019-01-29T21:34:30      2019-01-29     21:34:30
4     2019-01-29T21:32:49      2019-01-29     21:32:49

这不起作用,因为我的时间戳中间那个时髦的 "T",也可能是因为数据类型。

我需要删除 T 以便将其转换为标准的日期时间格式,然后我需要将日期和时间分开到它们自己的列中。奖励:我只想将小时带入自己的专栏。而不是 22:08:02,它只是 22.

您需要使用 pandas 时间戳:

>>> pd.Timestamp(‘2017-01-01T12’)
Timestamp(‘2017-01-01 12:00:00’)

所以:

df['StartTime'] = df["StartTime"].apply(lambda x: pd.Timestamp(x))

#now StartTime has the correct data type so you can access
# date and time methods as well as the hour

df['Date'] = df["StartTime"].apply(lambda x: x.date())
df['Time'] = df["StartTime"].apply(lambda x: x.time())
df['Hour'] = df["StartTime"].apply(lambda x: x.hour)

如@coldspeed 所述,调用 pd.to_datetime() 或 pd.Timesatmp() 会很好,只需省略 format 参数

解析时间戳 dateutil 太棒了。它可以从几乎任何字符串格式中计算出日期。

要从日期时间对象中获取小时,您可以使用 d.hour

您不需要格式化时间戳。 Pandas 可以将日期时间格式识别为“2019-01-29T21:34:30”。

输入:

import pandas as pd    
dt = '2019-01-29T21:34:30'    
pd.to_datetime(dt)

输出:

Timestamp('2019-01-29 21:11:15')