简体   繁体   English

在python中将int转换为日期

[英]converting int to date in python

i have the following column我有以下专栏

day
20190101
20190101
20190102
20190103

I want to change it to 01-01-2019 .我想将其更改为01-01-2019

I used the following code for that我为此使用了以下代码

data['day'] = pd.to_datetime(data['day'], format='%Y/%m/%d')

but it gives the following output instead: 1970-01-01 00:00:00.020190101但它提供了以下输出: 1970-01-01 00:00:00.020190101

data[["day"]] = data[["day"]].apply(pd.to_datetime)

also tried也试过

data['day'] = pd.to_datetime(data['day'], format='%Y/%m/%d')

expected output is 01-01-2019 but the actual output is 1970-01-01 00:00:00.020190101预期输出为01-01-2019但实际输出为1970-01-01 00:00:00.020190101

You can simply implement:您可以简单地实现:

def func(val):
    x = str(val)
    return '{}-{}-{}'.format(x[6:8],x[4:6],x[0:4])

And then run it for each entry.然后为每个条目运行它。

Just fix the format argument of to_datetime function, you have %Y/%m/%d while the actual format is %Y%m%d :只需修复to_datetime函数的format参数,您就有%Y/%m/%d而实际格式是%Y%m%d

df['dt'] = pd.to_datetime(df['day'], format='%Y%m%d')

print(df)

Output:输出:

        day         dt
0  20190101 2019-01-01
1  20190101 2019-01-01
2  20190102 2019-01-02
3  20190103 2019-01-03

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM