python - 在python(熊猫)中将通用日期转换为日期时间
问题描述
下午好,
我有一个巨大的数据集,其中时间信息以 float64(或整数)形式存储在数据帧的一列中,格式为“ddmmyyyy”(例如,2020 年 1 月 20 日将是浮点数 20012020.0)。我需要将其转换为像“dd-mm-yyyy”这样的日期时间。我看到了函数 to_datetime,但我无法真正获得我想要的东西。有人知道该怎么做吗?
马西莫
解决方案
您可以尝试转换为字符串,然后转换为日期格式,您想要这样:
# The first step is to change the type of the column,
# in order to get rid of the .0 we will change first to int and then to
# string
df["date"] = df["date"].astype(int)
df["date"] = df["date"].astype(str)
for i, row in df.iterrows():
# In case that the date format is similar to 20012020
x = str(df["date"].iloc[i])
if len(x) == 8:
df.at[i,'date'] = "{}-{}-{}".format(x[:2], x[2:4], x[4:])
# In case that the format is similar to 1012020
else:
df.at[i,'date'] = "0{}-{}-{}".format(x[0], x[1:3], x[3:])
编辑:
- 正如您所说,此解决方案仅在月份始终为 2 位时才有效。
- 在循环中添加了缺失的变量
- 在进入循环之前添加了更改列类型。
让我知道这是否有帮助!
推荐阅读
- python - 获取 TypeError:无法腌制 _thread.lock 对象
- php - wamp 服务器为绿色。未找到 $HTTP_GET_VARS 和 $_GET
- c++ - 获取参数的子类
- python - 如何以简单的方式将变量从 html 传递到 python?
- c# - 在阅读写入的内容之前,我是否需要“倒带”一个流?
- c# - 使用c#下载源代码时出错
- sql - 在 Dapper SqlBuilder 或 sp_exectuesql 中运行 SET 语句
- javascript - vue-router- 将查询参数从旧路由持久化到新路由的方式
- git - ssh 到远程时如何强制 git 使用不同的端口?
- python - Python将日期转换为日期时间