Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

python - Convert string date time to pandas datetime

I am new to Pandas and Python. I want to do some date time operations in my script. I am getting date time information from a csv file in following format: 01APR2017 6:59

How to convert it into pandas datetime format? Something like: 2017-04-01 06:59:00

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use to_datetime with parameter 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]

Another possible solution is use date_parser in read_csv:

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]

EDIT by comment:

If values cannot be parsed to datetime, add parameter errors='coerce' for convert to 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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...