如何在 Pandas 数据框中将对象转换为日期时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/22024338/
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 do I convert objects to datetime in a Pandas dataframe?
提问by Hugo
I have the following code to import from a CSV file
我有以下代码可以从 CSV 文件中导入
    data = pd.read_csv(("dados_meteo.csv"),\
               names=['POM','DTM','RNF','WET','HMD','TMP','DEW','INF'],\
               parse_dates = ['DTM'])
then
然后
 data.dtypes
returns
回报
POM     object
DTM     object
RNF    float64
WET    float64
HMD    float64
TMP    float64
DEW    float64
INF      int64
dtype: object
After using
使用后
data['DTM'] = data['DTM'].astype('datetime64[ns]')
The DTM keeps the same type. Could you help me?
DTM 保持相同的类型。你可以帮帮我吗?
Thank you
谢谢
回答by Chirag
Check your CSV file date column and make sure it is set to as date type ( or else select column=> right click =>Format cells=>Under category select Date=>and select date format)
检查您的 CSV 文件日期列并确保将其设置为日期类型(或者选择列 => 右键单击 => 设置单元格格式 => 在类别下选择日期 => 并选择日期格式)
then
然后
data =pd.read_csv("dados_meteo.csv",parse_dates=['date-coumn-name-here'])
回答by cyber-math
Once you created your data frame you could convert your object to date time type. Here is the way I did
创建数据框后,您可以将对象转换为日期时间类型。这是我做的方式
pd.to_datetime(data.DTM, errors = 'ignore')
If you do not have missing values in your raw data you might not need to use errors = 'ignore'
如果原始数据中没有缺失值,则可能不需要使用 errors = 'ignore'
Hope that helps!
希望有帮助!

