如何在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
How to convert string to datetime format in pandas python?
提问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 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
回答by Arjjun
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]')
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]'})
updated_df = df.astype({'timestamp':'datetime64[ns]'})