我是Pandas和Python的新手。我想在我的脚本中做一些日期时间操作。 我以下列格式从csv文件获取日期时间信息: 01APR2017 6:59
如何将其转换为pandas datetime格式?就像是: 2017-04-01 06:59:00
答案 0 :(得分:8)
您可以将http://spark.apache.org/docs/latest/submitting-applications.html#launching-applications-with-spark-submit与参数format
:
s = pd.Series(['01APR2017 6:59','01APR2017 6:59'])
print (s)
0 01APR2017 6:59
1 01APR2017 6:59
dtype: object
print (pd.to_datetime(s, format='%d%b%Y %H:%M'))
0 2017-04-01 06:59:00
1 2017-04-01 06:59:00
dtype: datetime64[ns]
另一种可能的解决方案是在to_datetime
中使用date_parser
:
import pandas as pd
from pandas.compat import StringIO
temp=u"""date
01APR2017 6:59
01APR2017 6:59"""
#after testing replace 'StringIO(temp)' to 'filename.csv'
parser = lambda x: pd.datetime.strptime(x, '%d%b%Y %H:%M')
df = pd.read_csv(StringIO(temp), parse_dates=[0], date_parser=parser)
print (df)
date
0 2017-04-01 06:59:00
1 2017-04-01 06:59:00
print (df.date.dtype)
datetime64[ns]
通过评论编辑:
如果无法将值解析为datetime
,请添加参数errors='coerce'
以转换为NaT
:
s = pd.Series(['01APR2017 6:59','01APR2017 6:59', 'a'])
print (s)
0 01APR2017 6:59
1 01APR2017 6:59
2 a
dtype: object
print (pd.to_datetime(s, format='%d%b%Y %H:%M', errors='coerce'))
0 2017-04-01 06:59:00
1 2017-04-01 06:59:00
2 NaT
dtype: datetime64[ns]