首页 > 解决方案 > 在python中将月-年格式更改为年-月-日格式

问题描述

我有一个 CSV 文件作为输入,其中一列的日期格式为年月。我需要将列格式更改为年-月-日格式,这意味着月末日期。我正在使用 Python 3。此外,我还在聚合函数和按函数分组中使用修改后的列。

例如:2020-01

2020-02

2020-03

2020-04

预期结果 :

2020-01-31

2020-02-29(考虑闰年)

2020-03-31

2020-04-30

很快...

标签: python

解决方案


from calendar import monthrange
from datetime import date
def month_end(year, month):
    return date(year=year, month=month, day=monthrange(year, month)[1]).isoformat()
>>> month_end(2020, 2)
'2020-02-29'

推荐阅读