python - 如何使用pymongo在mongodb中将整列从字符串类型转换为日期类型
问题描述
我的数据由 100 万行组成。示例如下所示:
_id:object("603678958a6eade21c0790b8")
id1:3758
date2:2010-01-01
time3:00:05:00
date4 :2009-12-31
time5:19:05:00
id6 :2
id7:-79.09
id8:35.97
id9:5.5
id10:0
id11:-99999
id12 :0
id13 :-9999
c14:"U"
id15:0
id16:99
id17:0
id18:-99
id19:-9999
id20:33
id21:0
id22:-99
id23:0
问题是 date2 和 date4 是我想要的形式,但它们是字符串,我想将它们转换为日期。我使用的代码如下所示:
df['date4'] = df['date4'].astype('datetime64[ns]')
df['date2'] = df['date2'].astype('datetime64[ns]')
df['time3'] = df['time3'].apply(lambda x:datetime.datetime.strptime(x[0]+x[1]+":"+x[2]+x[3], '%H:%M'))
df['time5'] = df['time5'].apply( lambda x: datetime.datetime.strptime(x[0] + x[1] + ":" + x[2] + x[3], '%H:%M'))
df['date2'] = df['date2'].apply(lambda x: arrow.get(x).format("YYYY-MM-DD"))
df['date4'] = df['date4'].apply(lambda x: arrow.get(x).format("YYYY-MM-DD"))
df['time3'] = df['time3'].apply(lambda x: arrow.get(x).format("HH:mm:ss"))
df['time5'] = df['time5'].apply(lambda x: arrow.get(x).format("HH:mm:ss"))
我需要在插入之前或之后转换它们吗?有谁知道我该怎么做?
解决方案
如果是我,我想将 date2/time3 和 date4/time5 合并为一列,如下所示:
df['date2'] = (df['date2']+'T'+df['time3']).astype('datetime64')
df['date4'] = (df['date4']+'T'+df['time5']).astype('datetime64')
推荐阅读
- rust - 为什么 js_sys::Atomics 操作需要 i32 类型的值?
- docusignapi - 在 Workato 中使用 Docusign Connector 时如何解决 USER_LACKS_PERMISSIONS 错误?
- r - R:“%in%”的更快版本?[修改]
- python - 如何创建一个可以直接从 shell 执行的程序(谐波和)?
- mysql - 以root身份登录mysql给我:用户'root'@'localhost'的访问被拒绝(使用密码:是)
- postgresql - WHERE 子句中不存在 SELECT AS 列
- java - WebFlux 注解 Controller Mono 空统一响应处理
- c - 如何在C中返回多个相同类型的参数(函数不是void)
- azure - 使用 OAuth2 从 Azure 数据工厂向 Azure DevOps 发出 REST API 请求
- git - 将分支合并到目录 GIT