简体   繁体   English

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

[英]How to convert string to datetime format in pandas python?

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_DATE 从字符串转换为数据时间格式并指定输入字符串的格式。 I saw some answers to this but its not for AM/PM format.我看到了一些答案,但它不适用于 AM/PM 格式。

Also, how to filter rows based on a range of dates in pandas?另外,如何根据熊猫中的日期范围过滤行?

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 dt accessor:要访问日期/日期/时间组件,请使用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

Approach: 1方法:1

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

you can use您可以使用

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

The result will be in this datetime format: 2019-03-04 00:08:48结果将采用以下datetime时间格式: 2019-03-04 00:08:48

Approach: 2方法:2

updated_df = df.astype({'timestamp':'datetime64[ns]'})
df['DateTime']=pd.to_datetime(df['Dates'],dayfirst=True,errors='ignore')

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

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