python - 在python中将月-年格式更改为年-月-日格式
问题描述
我有一个 CSV 文件作为输入,其中一列的日期格式为年月。我需要将列格式更改为年-月-日格式,这意味着月末日期。我正在使用 Python 3。此外,我还在聚合函数和按函数分组中使用修改后的列。
例如:2020-01
2020-02
2020-03
2020-04
预期结果 :
2020-01-31
2020-02-29(考虑闰年)
2020-03-31
2020-04-30
很快...
解决方案
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'
推荐阅读
- ruby-on-rails - 找不到未初始化的常量错误
- python - 如何查找列表元素是否包含在其他列表中但没有完全匹配
- macos - gdb 不能在 Mojave 10.14.2 上运行
- python - 从头开始实现 MLP 和在 PyTorch 中实现有什么区别?
- spring-boot - 如何告诉我的 dockerised Spring Boot Neo4J 应用程序与我的 Neo4j 服务器通信?
- rust - 如何为 Diesel 的通配符指定转义字符?
- python - Pandas - 检查是否有任何列是日期时间并将其更改为日期格式字符串(yyyy-mm-dd)
- c - 我将 tcp syn 数据包发送到一个不存在的 Ip,但没有得到响应
- json - 如何将 json 数据表单 web api 导入 SQL Server
- c++ - C++ 对象声明和无默认构造函数(用户声明或隐式声明)