代码之家  ›  专栏  ›  技术社区  ›  user3486773

在python中,如何从YYYYMM字符串日期中减去月份?

  •  0
  • user3486773  · 技术社区  · 5 年前

    我有日期字符串( YYYYMM 例如: 201909

    from datetime import datetime
    
    Month = '201905'
    Month = datetime.strptime(Month, '%Y%m').date()
    Month1 = str(Month -1)
    Month2 = str(Month -2)
    Month3 = str(Month -3)
    Month6 = str(Month -6)
    Month12 = str(Month - 100)
    

    这不起作用,但我希望能够将'Month'变量设置为类似'201905'的字符串,并从中计算各种YYYYMM字符串。

    2 回复  |  直到 5 年前
        1
  •  3
  •   s3dev    5 年前

    这个解决方案是两方面的 易于理解的 强健的 。它使用经过时间测试的内置软件包,将使您进入上一年,而不仅仅是从月数中减去(n)。

    from datetime import datetime as dt
    from dateutil.relativedelta import relativedelta
    
    # User's original values.
    string = '201905'
    dte = dt.strptime(string, '%Y%m').date()
    # Calculate one months previous.
    result = dte + relativedelta(months=-1)
    
    # Display path and results
    print('Original string value: {}'.format(string))
    print('Original datetime value: {}'.format(dte))
    print('Result (original minus two months): {}'.format(result))
    

    Original string value: 201905
    Original datetime value: 2019-05-01
    Result (original minus one month): 2019-04-01
    
        2
  •  0
  •   ex-punctis    5 年前

    old_date_string = '201901'
    decrement = 1
    year = int(old_date_string[:-2])
    month = int(old_date_string[-2:])
    month = month - decrement
    if month<1: 
      month = month + 12
      year = year - 1
    new_date_string = str(year) + '{:02d}'.format(month)
    print(new_date_string)
    
        3
  •  0
  •   Yatish Kadam    5 年前

    我正在利用这一事实,即它是一个字符串。 使用从字符串中提取最后两MM

    您需要检查的唯一条件是0。(我假设您将始终获得有效的YYYYMM。

    Month = '201912' 
    month = 12 if (int(Month[-2:]) -1 ) % 12 == 0 else (int(Month[-2:]) -1 ) % 12
    year = int(Month[:-2]) - 1 if month == 12 else int(Month[:-2])
    
    print (str(year)+str(month))
    
        4
  •  -2
  •   Shan Ali    5 年前

    这将给出所需的月份 int

    Month = '201905'
    Month = datetime.strptime(Month, '%Y%m').date()
    month = Month.month # this is an int, you can easily subtract it
    print (Month.month)