如何在pandas python中将字符串转换为日期时间格式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32204631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:12:20  来源:igfitidea点击:

How to convert string to datetime format in pandas python?

pythondatetimepandas

提问by GeorgeOfTheRF

I have a column I_DATE of type string(object) in a dataframe called train as show below.

我在名为 train 的数据框中有一列类型为 string(object) 的 I_DATE ,如下所示。

I_DATE
28-03-2012  2:15:00 PM
28-03-2012  2:17:28 PM
28-03-2012  2:50:50 PM

How to convert I_DATE from string to datatime format & specify the format of input string. I saw some answers to this but its not for AM/PM format.

如何将 I_DATE 从字符串转换为数据时间格式并指定输入字符串的格式。我看到了一些答案,但它不适用于 AM/PM 格式。

Also, how to filter rows based on a range of dates in pandas?

另外,如何根据熊猫中的日期范围过滤行?

采纳答案by EdChum

Use to_datetime, there is no need for a format string the parser is man/woman enough to handle it:

使用to_datetime,不需要解析器是男人/女人足以处理它的格式字符串:

In [51]:
pd.to_datetime(df['I_DATE'])

Out[51]:
0   2012-03-28 14:15:00
1   2012-03-28 14:17:28
2   2012-03-28 14:50:50
Name: I_DATE, dtype: datetime64[ns]

To access the date/day/time component use the dtaccessor:

要访问日期/日期/时间组件,请使用dt访问器:

In [54]:
df['I_DATE'].dt.date

Out[54]:
0    2012-03-28
1    2012-03-28
2    2012-03-28
dtype: object

In [56]:    
df['I_DATE'].dt.time

Out[56]:
0    14:15:00
1    14:17:28
2    14:50:50
dtype: object

You can use strings to filter as an example:

例如,您可以使用字符串进行过滤:

In [59]:
df = pd.DataFrame({'date':pd.date_range(start = dt.datetime(2015,1,1), end = dt.datetime.now())})
df[(df['date'] > '2015-02-04') & (df['date'] < '2015-02-10')]

Out[59]:
         date
35 2015-02-05
36 2015-02-06
37 2015-02-07
38 2015-02-08
39 2015-02-09

回答by Arjjun

Approach: 1

方法:1

Given original stringformat: 2019/03/04 00:08:48

给定原始string格式:2019/03/04 00:08:48

you can use

您可以使用

updated_df = df['timestamp'].astype('datetime64[ns]')

updated_df = df['timestamp'].astype('datetime64[ns]')

The result will be in this datetimeformat: 2019-03-04 00:08:48

结果将采用以下datetime格式:2019-03-04 00:08:48

Approach: 2

方法:2

updated_df = df.astype({'timestamp':'datetime64[ns]'})

updated_df = df.astype({'timestamp':'datetime64[ns]'})