Python中的时间函数datetime.timedelta()

Python中的时间函数

    • 时间上的加减

时间上的加减

getday() 返回在某年某月某日的基础上加n天后的年月日

import datetime
import json
import random
import time
import string

def getday(y=2017, m=8, d=15, n=1):
    the_date = datetime.datetime(y,m,d)
    result_date = the_date + datetime.timedelta(days=n)  #加n天后的日期
    d = result_date.strftime('%Y%m%d')  #格式化成字符串形式
    year = int(d[:4])
    month = int(d[4:6])
    day = int(d[6:8])
    return d,(year,month,day)
 
d, _ = getday(2022,10,11, 20)

获取n小时后的时间

def get_later_time(cur_time, n):
    '''
    :param cur_time: 当前时间 如2022040810  年月日时
    :param n: 单位为 h, 获取n小时后的时间
    :return:
    '''
    the_date = datetime.datetime.strptime(cur_time, '%Y%m%d%H')
    result_date = the_date + datetime.timedelta(hour=n)
    d = result_date.strftime('%Y%m%d%H')
    return d

获取hours小时,minutes分钟后的时间。

the_date = datetime.datetime.strptime(cur_time, '%Y%m%d%H%M%S')
print(the_date)
##datetime.timedelta() 进行时间上的加减,参数可以是(days,hours,minutes,seconds)等
result_date = the_date + datetime.timedelta(hours=2,minutes =20)   
print(result_date)

函数说明:class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

获取 d 天 h小时 m分钟 s秒之前的时间

def get_before_time(cur_time):
    '''

    :param cur_time: 当前时间 如20221012013130  年月日时分秒
    :param duration:
    :return: h小时 m分钟 s秒之前的时间
    '''
    d =random.randint(0,1)
    h = random.randint(0, 23)
    m = random.randint(0, 59)
    s = random.randint(0, 59)
    the_date = datetime.datetime.strptime(cur_time, '%Y%m%d%H%M%S')
    result_date = the_date - datetime.timedelta(days=d,hours=h,minutes=m,seconds=s)
    result = result_date.strftime('%Y%m%d%H%M%S')
    return result

以时间格式输出:

cur_time='20220909221050'
the_date = datetime.datetime.strptime(cur_time, '%Y%m%d%H%M%S') #转成时间格式
print(the_date)
# 输出结果:2022-09-09 22:10:50result = the_date.strftime('%Y%m%d%H%M%S')
result = the_date.strftime('%Y%m%d%H%M%S')  #转成字符串
print(result[:4])
# 输出结果:2022

你可能感兴趣的:(python基础知识,python)