Python教程

python时间的处理

本文主要是介绍python时间的处理,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

日期偏移

import datetime

from dateutil.relativedelta import relativedelta


def date_add(date, seconds=0, minutes=0, hours=0, days=0, months=0, years=0):
    date = date + datetime.timedelta(seconds=seconds, minutes=minutes, hours=hours, days=days)
    date = date + relativedelta(months=months)
    date = datetime.datetime(year=date.year + years, month=date.month, day=date.day, hour=date.hour,
                             minute=date.minute, second=date.second)
    return date


now = datetime.datetime.now()
date = date_add(now, months=-13)
print(date)

 

获取月份的第一天和最后一天

import calendar
import datetime

now = datetime.date.today()
this_month_start = datetime.datetime(now.year, now.month, 1)
this_month_end = datetime.datetime(now.year, now.month, calendar.monthrange(now.year, now.month)[1])

print(this_month_start)
print(this_month_end)

  

这篇关于python时间的处理的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!