在python中将整数(yyyy mm dd)转换为日期格式(mm/dd/yyyy)

2024-05-13 04:11:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据框。

id int_date  
1  20160228  
2  20161231  
3  20160618  
4  20170123  
5  20151124

如何将上述日期以int格式转换为mm/dd/yyyy格式?希望以特定格式进行进一步的excel操作吗?

id int_date  
1  02/28/2016  
2  12/31/2016  
3  06/18/2016
4  01/23/2017
5  11/24/2015

是否也可以生成只有月份的第三列?比如一月,二月等国际日期?

我试着跟着

date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))

但日期在datetime对象中,如何将其作为日期放在pandas DF中?


Tags: 数据iddatetimedate格式excelyeardd
3条回答

一定会有更好的解决方案,但是既然您的日期中有零而不是一位数元素(即06而不是6),为什么不直接将其转换为字符串并转换子部分呢?

使用datetime还可以获得月字符串等

//编辑: 更确切地说,应该是这样的:

def get_datetime(date):
    date_string = str(date)
    return datetime.date(date_string[:3], date_string[4:6], date_string[6:8]

使用applymap新建列:

import pandas as pd

dates = [
    20160228,
    20161231,
    20160618,
    20170123,
    20151124,
]

df = pd.DataFrame(data=list(enumerate(dates, start=1)), columns=['id','int_date'])

df[['str_date']] = df[['int_date']].applymap(str).applymap(lambda s: "{}/{}/{}".format(s[4:6],s[6:], s[0:4]))

print(df)

发射:

$ python test.py
   id  int_date    str_date
0   1  20160228  02/28/2016
1   2  20161231  12/31/2016
2   3  20160618  06/18/2016
3   4  20170123  01/23/2017
4   5  20151124  11/24/2015

您可以使用datetime方法。

from datetime import datetime
a = '20160228'
date = datetime.strptime(a, '%Y%m%d').strftime('%m/%d/%Y')

祝你好运

相关问题 更多 >