翻墙被狗咬
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Python处理月份依次加一

最近需要用的一个小程序从 2000-01-01 00:00:00 按照每月递增加1的方式。

看了一下别人写的都奇奇怪怪的。简单点可以这样:

import datetime


FORMATSTRING = "%Y-%m-%d %H:%M:%S"


def time_handle(date):
    """处理月份依次加一
    :param date:
    :return:
    """
    strptime = datetime.datetime.strptime(date, FORMATSTRING)
    month = 1 if strptime.month == 12 else strptime.month + 1
    year = strptime.year + 1 if strptime.month == 12 else strptime.year
    return strptime.replace(year=year, month=month)


if __name__ == '__main__':
    print(time_handle("2016-12-01 00:01:00"))