简体   繁体   English

Pandas 中的日期时间转换问题

[英]Problem with datetime conversion in Pandas

Here is a reproduced example of my problem :这是我的问题的复制示例:

df = pd.DataFrame(["2018-01-13 17:25:54+0100",
    "2018-01-13 07:23:36+0100",
    "2018-01-13 08:15:48+0100"], columns=["date"])

print(type(datetime.strptime(df["date"][1], '%Y-%m-%d %H:%M:%S%z')))

print(type(pd.Series(df["date"].apply(lambda s: datetime.strptime(s, '%Y-%m-%d %H:%M:%S%z')))[1]))

The output are :输出是:

class 'datetime.datetime'类“日期时间.日期时间”

class 'pandas._libs.tslibs.timestamps.Timestamp'类'pandas._libs.tslibs.timestamps.Timestamp'

How can I get a datetime.datetime object by using the apply function (or a similar one)?如何使用 apply 函数(或类似函数)获取 datetime.datetime 对象?

Use Pandas methods for datetime operations使用 Pandas 方法进行datetime操作

In general, avoid the datetime module from the standard library when dealing with Pandas dataframes.通常,在处理 Pandas 数据帧时,避免使用标准库中的datetime模块。 You should want to use vectorised operations, and should rely on Pandas methods taking advantage of NumPy-based vectorisation:应该希望使用矢量化操作,并且应该依靠 Pandas 方法利用基于 NumPy 的矢量化:

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

print(df['date'].dtype)
# datetime64[ns]

But if you insist...但是如果你坚持...

If you wish to export to an array of datetime.datetime values for use outside of Pandas, you can use to_pydatetime :如果您希望导出到一组datetime.datetime值以供在 Pandas 之外使用,您可以使用to_pydatetime

py_date = df['date'].dt.to_pydatetime()
# array([datetime.datetime(2018, 1, 13, 16, 25, 54),
#        datetime.datetime(2018, 1, 13, 6, 23, 36),
#        datetime.datetime(2018, 1, 13, 7, 15, 48)], dtype=object)

However, once you are using Pandas there's rarely a need to do so.但是,一旦您使用了 Pandas,就很少需要这样做了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM