【问题标题】:Pandas datetime, converting monthly date to month end day熊猫日期时间,将每月日期转换为月末日期
【发布时间】:2021-12-06 15:15:54
【问题描述】:

尝试使用日期时间获取月末数据。

我的代码:

monthyear = input("Enter Full Month and Year: ")   #Ie September 2021
assessdate = pd.to_datetime(prevdate, format="%B %Y").strftime('%m%d%Y %H:%M')

得到

09012021 00:00

期待:

09/30/2021 00:00

试过了:

monthyear = input("Enter Full Month and Year: ")   #Ie September 2021
assessdate = pd.to_datetime(monthyear, format="%B %Y")+MonthEnd(1).dt.strftime('%m%d%Y %H:%M')

【问题讨论】:

    标签: pandas


    【解决方案1】:

    我们有几个问题:

    1. 一旦我们解决了整个日期,我们只想strftime。出于这个原因,我们需要在偏移计算周围加上括号。
    2. MonthEnd(1) 通常不是我们希望在本月底得到的。我们要MonthEnd(0)
    3. 缺少格式字符串/

    所有这些看起来像:

    import pandas as pd
    from pandas.tseries.offsets import MonthEnd
    
    month_year = input("Enter Full Month and Year: ")  # Ie September 2021
    assess_date = (
            pd.to_datetime(month_year, format="%B %Y") + MonthEnd(0)
    ).strftime('%m/%d/%Y %H:%M')
    print(assess_date)
    

    程序输入/输出:

    Enter Full Month and Year: September 2021
    09/30/2021 00:00
    

    MonthEnd(1)MonthEnd(0) 的区别在于,如果是当月的最后一天,结果会有所不同:

    pd.Timestamp('2021-09-30') + MonthEnd(1)  # 2021-10-31 00:00:00
    pd.Timestamp('2021-09-30') + MonthEnd(0)  # 2021-09-30 00:00:00
    

    【讨论】:

    • 谢谢,你知道如何在09之前去掉0吗?
    • 在月份模式前添加#-,具体取决于操作系统。对于 windows ('%#m/%d/%Y %H:%M') 或对于 linux/mac ('%-m/%d/%Y %H:%M') more details here
    猜你喜欢
    • 2017-12-12
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多