在python中将对象转换为日期时间格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38333954/
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 20:40:04  来源:igfitidea点击:

Converting object to datetime format in python

pythondatetimepandas

提问by Sdotsey

Below is the first row of my csv DateTime column:

下面是我的 csv DateTime 列的第一行:

Mon Nov 02 20:37:10 GMT+00:00 2015

2015 年 11 月 2 日星期一 20:37:10 GMT+00:00

The DateTime column is currently an object and I want to convert it to datetime format so that I can get the date to appear as 2015-11-02 and I will create a separate column for the time.

DateTime 列当前是一个对象,我想将其转换为日期时间格式,以便日期显示为 2015-11-02,我将为该时间创建一个单独的列。

The code I am using to convert the column to date time format is:

我用来将列转换为日期时间格式的代码是:

for item, frame in df['DateTime'].iteritems():
     datetime.datetime.strptime(df['DateTime'], "%a-%b-%d-%H-%M-%S-%Z-%Y")

I am getting this error: TypeError: must be str, not Series

我收到此错误:TypeError: must be str, not Series

Any help would be greatly appreciated!

任何帮助将不胜感激!

回答by Alberto Garcia-Raboso

Use pd.to_datetime():

使用pd.to_datetime()

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

For example,

例如,

pd.to_datetime('Mon Nov 02 20:37:10 GMT+00:00 2015')

produces Timestamp('2015-11-02 20:37:10').

产生Timestamp('2015-11-02 20:37:10').