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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43133605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:34:06  来源:igfitidea点击:

Convert integer (YYYYMMDD) to date format (mm/dd/yyyy) in python

pythonpandasdate

提问by Sushant Kulkarni

I have following dataframe.

我有以下数据框。

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

How to convert above date in int format to date format of mm/dd/yyyy? Want this in particular format for further excel operations?

如何将上述 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

IS it also possible to generate third column with only Month in words? like January, February etc from int_date?

是否也可以用单词生成第三列?像 int_date 的一月、二月等?

I tried following

我试过

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

but date is in datetime object, how to put it as date in pandas DF?

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

回答by Mr Sam

You can use datetimemethods.

您可以使用datetime方法。

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

Good Luck;

祝你好运;

回答by aghast

Build a new column with applymap:

使用以下命令构建一个新列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)

Emits:

发射:

$ 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

回答by N. Walter

There is bound to be a better solution to this, but since you have zeroes instead of single-digit elements in your date (i.e. 06 instead of 6), why not just convert it to string and convert the subsections?

肯定会有更好的解决方案,但是由于您的日期中有零而不是个位数元素(即 06 而不是 6),为什么不将其转换为字符串并转换小节?

using datetime would also get you the month strings etc.

使用 datetime 也会为您提供月份字符串等。

//edit: to be a little more precise, something like this should do the job:

//编辑:更精确一点,这样的事情应该可以完成这项工作:

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