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
277 views
in Technique[技术] by (71.8m points)

python - In Pandas how do I convert a string of date strings to datetime objects and put them in a DataFrame?

import pandas as pd
date_stngs = ('2008-12-20','2008-12-21','2008-12-22','2008-12-23')

a = pd.Series(range(4),index = (range(4)))

for idx, date in enumerate(date_stngs):
    a[idx]= pd.to_datetime(date)

This code bit produces error:

TypeError:" 'int' object is not iterable"

Can anyone tell me how to get this series of date time strings into a DataFrame as DateTime objects?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
>>> import pandas as pd
>>> date_stngs = ('2008-12-20','2008-12-21','2008-12-22','2008-12-23')
>>> a = pd.Series([pd.to_datetime(date) for date in date_stngs])
>>> a
0    2008-12-20 00:00:00
1    2008-12-21 00:00:00
2    2008-12-22 00:00:00
3    2008-12-23 00:00:00

UPDATE

Use pandas.to_datetime(pd.Series(..)). It's concise and much faster than above code.

>>> pd.to_datetime(pd.Series(date_stngs))
0   2008-12-20 00:00:00
1   2008-12-21 00:00:00
2   2008-12-22 00:00:00
3   2008-12-23 00:00:00

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

...