首页 > 解决方案 > 在python(熊猫)中将通用日期转换为日期时间

问题描述

下午好,

我有一个巨大的数据集,其中时间信息以 float64(或整数)形式存储在数据帧的一列中,格式为“ddmmyyyy”(例如,2020 年 1 月 20 日将是浮点数 20012020.0)。我需要将其转换为像“dd-mm-yyyy”这样的日期时间。我看到了函数 to_datetime,但我无法真正获得我想要的东西。有人知道该怎么做吗?

马西莫

标签: pythondatetimetype-conversion

解决方案


您可以尝试转换为字符串,然后转换为日期格式,您想要这样:

# 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 位时才有效。
  • 在循环中添加了缺失的变量
  • 在进入循环之前添加了更改列类型。

让我知道这是否有帮助!


推荐阅读