【问题标题】:Convert integer (YYYYMMDD) to date format (mm/dd/yyyy) in python [duplicate]在python中将整数(YYYYMMDD)转换为日期格式(mm/dd/yyyy)[重复]
【发布时间】:2017-08-25 07:23:13
【问题描述】:

我有以下数据框。

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

是否也可以生成仅包含月份的第三列?比如 int_date 的 1 月、2 月等?

我试过了

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

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

【问题讨论】:

  • 这个问题是 pandas 数据框中的一列,在这种情况下,逐项应用转换是不合适的,并且不是标记问题的重复。更好的答案是stackoverflow.com/questions/27506367/…

标签: python pandas date


【解决方案1】:

使用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

【讨论】:

    【解决方案2】:

    您可以使用datetime 方法。

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

    祝你好运;

    【讨论】:

    • 谢谢!这有效
    【解决方案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]
    

    【讨论】:

    • 为了使最后一行工作,它应该是这样的:datetime.date(int(date_string[0:4]), int(date_string[4:6]), int(date_string[6:8]))
    猜你喜欢
    • 1970-01-01
    • 2018-04-28
    • 1970-01-01
    • 1970-01-01
    • 2012-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-09
    相关资源
    最近更新 更多