python日期加减操作

这里对python操作日期做一个记录

import datetime
import random
import copy
from dateutil.relativedelta import relativedelta

tf = "2020-01-01 10:10:10"
timelist = []


def dischargeDate(admit_date):
    # print(f"admit_date: {admit_date}")
    admit_date_arry = datetime.datetime.strptime(
        admit_date, "%Y-%m-%d %H:%S:%M")
    # 随机生成需要增加的小时
    steptime = random.randint(24, 337)
    # print(f"steptime: {steptime}")

    # 将小时转化为: X天Y小时的形式
    days = steptime // 24
    # print(f"days: {days}")
    hours = steptime % 24
    # print(f"hours: {hours}")
    # 使用relativedelta,years=0, months=0, days=0, leapdays=0, weeks=0,
    #  hours=0, minutes=0, seconds=0, microseconds=0, 可以实现日期的加减
    # 在原来的基础上日期加X天Y小时
    discharge_date_arry = (
        admit_date_arry + relativedelta(days=days, hours=hours))
    timelist = [admit_date_arry.strftime('%Y-%m-%dT%H:%S:%MZ'),
                discharge_date_arry.strftime('%Y-%m-%dT%H:%S:%MZ'),
                admit_date_arry.strftime('%Y-%m-%d %H:%S:%M')]
    re = discharge_date_arry.strftime('%Y-%m-%d %H:%S:%M')
    # print(f"re: {re}")
    return re, timelist


def _date(admit_date, count):
    re = []
    a = admit_date
    for i in range(count):
        # print(a)
        b, timelist = dischargeDate(a)
        re.append(timelist)
        a = copy.deepcopy(b)
        # print(a)
    print(re)


_date(tf, 10)

输出:
PS D:\PythonWorkspace\IP20> & "D:/Program Files (x86)/Python3.9/python.exe" d:/PythonWorkspace/IP20/common/create_time.py [['2020-01-01T10:10:10Z', '2020-01-03T13:10:10Z', '2020-01-01 10:10:10'], ['2020-01-03T13:10:10Z', '2020-01-09T17:10:10Z', '2020-01-03 13:10:10'], ['2020-01-09T17:10:10Z', '2020-01-20T20:10:10Z', '2020-01-09 17:10:10'], ['2020-01-20T20:10:10Z', '2020-02-02T07:10:10Z', '2020-01-20 20:10:10'], ['2020-02-02T07:10:10Z', '2020-02-12T00:10:10Z', '2020-02-02 07:10:10'], ['2020-02-12T00:10:10Z', '2020-02-25T00:10:10Z', '2020-02-12 00:10:10'], ['2020-02-25T00:10:10Z', '2020-02-27T19:10:10Z', '2020-02-25 00:10:10'], ['2020-02-27T19:10:10Z', '2020-03-01T10:10:10Z', '2020-02-27 19:10:10'], ['2020-03-01T10:10:10Z', '2020-03-05T16:10:10Z', '2020-03-01 10:10:10'], ['2020-03-05T16:10:10Z', '2020-03-07T23:10:10Z', '2020-03-05 16:10:10']]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值