转换并替换%Y%m%d%H%M'到数据帧字典中的日期时间

时间:2018-01-09 14:10:03

标签: python-3.x pandas datetime dictionary dataframe

你好我希望转换一个&%;%Y%m%d%H%M'到日期时间并将其替换为数据帧字典。

import pandas as pd
import time

df1 = pd.DataFrame(data= {'col1':['201706202359' , '201706220510'], "col2" : ['0', '1']})
df2 = pd.DataFrame(data= {'col1':['201707202300' , '201706230600'],"col2" : ['0', '1']})


dfs = {'df1' : df1, 'df2' : df2}

for name, df in dfs.items():

    for i in range(len(df)):
        timestamp = time.strptime(str(df[["col1"]].iloc[i][0]), '%Y%m%d%H%M')
        datetime = pd.to_datetime((str(timestamp[2])+"-"+str(timestamp[1])+"-"+str(timestamp[0])+" "+ str(timestamp[3])+":"+ str(timestamp[4])+":"+ str(timestamp[5])))

但是我无法替换转换后的col1col1现在是{{1}}中的时间戳。 我怎么能这样做呢。

提前谢谢你。

1 个答案:

答案 0 :(得分:2)

IIUC:

In [330]: for x in dfs:
     ...:     dfs[x]['col1'] = pd.to_datetime(dfs[x]['col1'], format='%Y%m%d%H%M')
     ...:

In [331]: dfs
Out[331]:
{'df1':                  col1 col2
 0 2017-06-20 23:59:00    0
 1 2017-06-22 05:10:00    1, 'df2':                  col1 col2
 0 2017-07-20 23:00:00    0
 1 2017-06-23 06:00:00    1}

In [332]: dfs['df1']
Out[332]:
                 col1 col2
0 2017-06-20 23:59:00    0
1 2017-06-22 05:10:00    1

请注意,它也改变了原始DF:

In [340]: df1
Out[340]:
                 col1 col2
0 2017-06-20 23:59:00    0
1 2017-06-22 05:10:00    1

In [341]: df2
Out[341]:
                 col1 col2
0 2017-07-20 23:00:00    0
1 2017-06-23 06:00:00    1