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']]