Python / Pandas将字符串解析为日期和时间

时间:2018-10-19 16:57:14

标签: python-3.x pandas datetime

我有一个数据框,其中的一列包含表示日期和时间的字符串,如下所示:

0    Fri Oct 19 17:42:31 2018
1    Fri Oct 19 17:42:31 2018
2    Fri Oct 19 17:42:31 2018
3    Fri Oct 19 17:42:31 2018
4    Fri Oct 19 17:42:31 2018

如何解析字符串以获取日期时间格式的时间和数据?

2 个答案:

答案 0 :(得分:3)

只需使用pd.to_datetime()

import pandas as pd

df = pd.DataFrame([
['Fri Oct 19 17:42:31 2018'],
['Fri Oct 19 17:42:31 2018'],
['Fri Oct 19 17:42:31 2018'],
['Fri Oct 19 17:42:31 2018'],
['Fri Oct 19 17:42:31 2018']],
columns=['Date'])

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

收益:

                 Date
0 2018-10-19 17:42:31
1 2018-10-19 17:42:31
2 2018-10-19 17:42:31
3 2018-10-19 17:42:31
4 2018-10-19 17:42:31

根据@ALollz的评论,您可以指定格式以提高性能:

df['Date'] = pd.to_datetime(df['Date'], format='%a %b %d %H:%M:%S %Y')

答案 1 :(得分:1)

您可以尝试describe('MyCustomComponent', () => { let component: MyCustomComponent; let fixture: ComponentFixture<MyCustomComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ MyCustomComponent, MyCustomDirective ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(MyCustomComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('displays a button with the directive', () => { const buttonWithDirective = fixture.debugElement.query(By.css('#with-directive')); const directiveInstance: MyCustomDirective = buttonWithDirective.injector.get(MyCustomDirective); expect(directiveInstance.myVariable).toBe('hello there!'); const buttonWithoutDirective = fixture.debugElement.query(By.css('#without-directive')); //danger!! this will throw an exception because there is no directive //const directiveInstance: MyCustomDirective = buttonWithDirective.injector.get(MyCustomDirective); }); }); 。这会将字符串中的日期时间转换为日期时间对象,并存储在同一列中。让我知道这是否适用于您的数据框。您必须df['column_name']=pd.to_datetime(df['column_name'])才能运行。