将datetime64[ns, UTC] Pandas列转换为日期时间

29

我有一个包含时间戳的数据框,其数据类型为对象。

0    2020-07-09T04:23:50.267Z
1    2020-07-09T11:21:55.536Z
2    2020-07-09T11:23:18.015Z
3    2020-07-09T04:03:28.581Z
4    2020-07-09T04:03:33.874Z
Name: timestamp, dtype: object

我不知道上面的数据框中日期时间的格式。我对上述列应用了 pd.to_datetime,其中数据类型被更改为 datetime64[ns, UTC]

df['timestamp'] = pd.to_datetime(df.timestamp)

现在数据框的外观如下:

0   2020-07-09 04:23:50.267000+00:00
1   2020-07-09 11:21:55.536000+00:00
2   2020-07-09 11:23:18.015000+00:00
3   2020-07-09 04:03:28.581000+00:00
4   2020-07-09 04:03:33.874000+00:00
Name: timestamp, dtype: datetime64[ns, UTC]

我想将上述的 datetime64[ns, UTC] 格式转换为普通日期时间格式。

For example,
2020-07-09 04:23:50.267000+00:00  to 2020-07-09 04:23:50

有人能解释一下这个2020-07-09T04:23:50.267Z表示的含义吗?还有如何将其转换为日期时间对象?


2
请将 Pandas 时区感知的 DatetimeIndex 转换为特定时区的本地时间戳,但是以简单时间格式表示。可以参考以下链接:https://dev59.com/t2Qn5IYBdhLWcg3wto9W - deadshot
2020-07-09T04:23:50.267Z 是一个 ISO8601 的日期/时间字符串。Z 代表的是 Zulu 时间,意味着协调世界时(UTC)。 - FObersteiner
2个回答

56
要删除时区,请使用tz_localize:
df['timestamp'] = pd.to_datetime(df.timestamp).dt.tz_localize(None)

输出:

                timestamp
0 2020-07-09 04:23:50.267
1 2020-07-09 11:21:55.536
2 2020-07-09 11:23:18.015
3 2020-07-09 04:03:28.581
4 2020-07-09 04:03:33.874

1
由于输入已经是UTC时间,我建议转换为None而不是本地化,请参见我的答案这里 - FObersteiner

4

to_datetime函数的返回结果会根据输入数据的类型而变化[对我来说有点令人困惑]:

list-like: DatetimeIndex
Series: Series of datetime64 dtype
scalar: Timestamp

所以以下操作失败。
df["Time"] = pd.to_datetime(df["StringArray"])
xm = df["Time"] < pd.to_datetime("12/29/2020  9:09:37 PM")

但是以下内容完全正常。

df["Time"] = pd.to_datetime(df["StringArray"])
xm = df["Time"] < pd.to_datetime("12/29/2020  9:09:37 PM", utc=True)

这可能有助于您避免时区问题。祝好!

我正在努力进行比较,如果df["Time"]中的datetime64[ns, UTC]具有任何NaT值,则无法使用np.isnat工作。(如果xm = ((np.isnat(df["Time"])) | (df["Time"] < pd.to_datetime("12/29/2020 9:09:37 PM", utc=True))),我会收到TypeError: ufunc 'isnat' is only defined for np.datetime64 and np.timedelta64.因此,可能需要使用tz_localize?(请注意,pandas具有pd.NaT常量,但没有pd.isnat()或pd.Timestamp.isnat()函数) - mpag

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接