使用str中的常量值在pandas df中添加日期列

Shu*_*m R 8 python python-2.7 python-3.x pandas

我在 Pandas df 中有一张桌子

    product_id_x    product_id_y    count
0   2727846            7872456       1
1   29234              2932348       2
2   29346              9137500       1
3   29453              91365738      1
4   2933666            91323494      1
Run Code Online (Sandbox Code Playgroud)

我想添加一个我在 str 中定义的新列“日期”。

dateSelect = "'2016-11-06'"
Run Code Online (Sandbox Code Playgroud)

所以我添加了一个新的常量列

df['dates'] = dateSelect 
Run Code Online (Sandbox Code Playgroud)

但我得到的结果是

   product_id_x   product_id_y    count   dates
0   2727846          7872456         1  '2016-11-06'
1   29234            2932348         2  '2016-11-06'
2   29346            9137500         1  '2016-11-06'
3   29453            91365738        1  '2016-11-06'
4   2933666          91323494        1  '2016-11-06'
Run Code Online (Sandbox Code Playgroud)

日期中的值用引号引起来。和

type(df['dates']) = str
Run Code Online (Sandbox Code Playgroud)

但我想要日期格式,因为我将进一步将此表存储在我的 mysql 数据库中。我希望类型是日期。

from sqlalchemy import create_engine
engine = create_engine('mysql+mysqldb://name:pwd@xxx.xx.xx.x/dbname', echo=False)
df.to_sql(name='tablename', con=engine, if_exists = 'append', index=False)
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 6

我认为您可以先使用replace '空格,然后使用to_datetime

dateSelect = pd.to_datetime("'2016-11-06'".replace("'",""))
print (dateSelect)
2016-11-06 00:00:00

print (type(dateSelect))
<class 'pandas.tslib.Timestamp'>
Run Code Online (Sandbox Code Playgroud)
df['dates'] = pd.to_datetime("'2016-11-06'".replace("'",""))

print (df)
   product_id_x  product_id_y  count      dates
0       2727846       7872456      1 2016-11-06
1         29234       2932348      2 2016-11-06
2         29346       9137500      1 2016-11-06
3         29453      91365738      1 2016-11-06
4       2933666      91323494      1 2016-11-06

print (df.dtypes)
product_id_x             int64
product_id_y             int64
count                    int64
dates           datetime64[ns]
dtype: object
Run Code Online (Sandbox Code Playgroud)


piR*_*red 6

最直接的路线

df['dates'] = pd.Timestamp('2016-11-06')
df

   product_id_x  product_id_y  count      dates
0       2727846       7872456      1 2016-11-06
1         29234       2932348      2 2016-11-06
2         29346       9137500      1 2016-11-06
3         29453      91365738      1 2016-11-06
4       2933666      91323494      1 2016-11-06
Run Code Online (Sandbox Code Playgroud)