【问题标题】:convert a generic date into datetime in python (pandas)在python(熊猫)中将通用日期转换为日期时间
【发布时间】:2020-03-21 16:56:40
【问题描述】:

下午好,

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

马西莫

【问题讨论】:

    标签: python datetime type-conversion


    【解决方案1】:

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

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

    如果这有帮助,请告诉我!

    【讨论】:

    • EnriqueBet,不幸的是我收到错误“'int' object is not subscriptable”。
    • 对不起,我的括号是不好的地方,我刚刚编辑了代码,你能再试一次吗?
    • EnriqueBet,谢谢!这适用于像 20122020 这样的整数日期,但对于像 9012020(2020 年 1 月 9 日)这样的日期,代码不起作用。年份和月份总是以两位数存储,但日期有时是 1 位(1 到 9),有时是 2 位(10 到月末)。
    • 我应该在格式化后在 df['date'] 中添加 x 吗?因为在这种情况下 x 是未定义的
    • 非常感谢,现在我更正了数据框,它工作顺利! ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 2020-12-18
    • 2021-12-06
    • 2017-05-20
    • 2018-12-08
    相关资源
    最近更新 更多