python中怎么获取每月的最后一天的日期?

  统计/机器学习 Python    浏览次数:2224        分享
0

python中怎么获取每月的最后一天?比如2019年11月,最后一天是'2019-11-30';比如2020年2月,最后一天是'2020-02-29'。

 

潇洒橙   2020-08-05 22:09



   2个回答 
4

可以用calendar 获取每月的总天数,总天数就是每月的最后一天。

>>> import calendar
>>> calendar.monthrange(2020,2)[1]
29
>>> calendar.monthrange(2019,11)[1]
30
SofaSofa数据科学社区DS面试题库 DS面经

YYANG   2020-08-06 00:54

多谢! - 潇洒橙   2020-08-07 20:40
1


import calendar
def last_day_month(year, month):
    if month < 10:
        return str(year) + '-0' + str(month) + '-' + str(calendar.monthrange(year, month)[1])
    return str(year) + '-0' + str(month) + '-' + str(calendar.monthrange(year, month)[1])

可以输入last_day_month(2020, 2),可以得到'2020-02-29'

SofaSofa数据科学社区DS面试题库 DS面经

wxw_pku   2020-09-07 13:41



  相关讨论

pyton两个dict如何合并?如果key有重复,取最小值

如何对将Python dictionary里的key按照value进行排序?

怎么在python获取系统的当前日期和时间?

怎么用python批量生成含重复数值的数列?

python 时间格式问题

python里有没有类似matlab里linspace的功能?

python怎么往集合里增加元素(类似append)?

python里有没有类似excel里的那种数据透视表?

如何像访问本地文件系统一样访问云存储?

python里的TYPE_CHECKING是什么作用?

  随便看看

为啥Xgboost比GradientBoost好那么多?

pandas.DataFrame的index重新排列(从0开始)

为什么机器学习中的优化问题很少用到牛顿法?

在使用PCA降维时,有哪些坑?

前馈神经网络如何选择隐藏层的数量