Python之 datetime模块中strptime和strftime的区别 一、区别

 datetime.datetime.strptime(字符串,时间格式):给定一个时间字符串和时间格式,返回一个datetime 时间对象

 datetime.datetime.strftime(时间对象,输出格式):给定一个时间对象和输出格式,返回一个时间字符串

import datetime
start_time='2020-11-18 10:00:00'#时间字符串
time=datetime.datetime.strptime(start_time,'%Y-%m-%d %H:%M:%S')#返回datetime时间对象
print(type(time))
---------执行结果------
<class 'datetime.datetime'>

end_time=datetime.datetime.strftime(time,'%Y-%m-%d %H:%M:%S')#time是时间对象,后面跟输出格式
print(type(end_time))#返回的是一个时间字符串
-------执行结果------
<class 'str'>

datetime.timedelta(minutes=20)返回的是一个时间对象,所以要算时间差,必须是两个时间对象相加才行

host='XXX.XX.1.4'
port=3306
user='user'
passwd='XXX'
db='XXXX'
charset='utf8'
#需求是往数据表插入datetime间隔15min的96条数据
import time,datetime
import  pymysql
conn=pymysql.connect(host=host,port=port,user=user,passwd=passwd,db=db,charset=charset,autocommit=True)#连接数据库
cursor=conn.cursor()#创建游标
data_time = "2020-11-18 00:00:00"#
for i in range(0,96):
    customer_code='JH-100-4'
    company_id=140
    p=23
    create_time="2020-11-18 09:00:00"
    sql="insert into cust_rep_data (customer_code,company_id,p,data_time,create_time) values('%s','%d','%d','%s','%s');" %(customer_code,company_id,p,data_time,create_time)
    cursor.execute(sql)
    # print(cursor.fetchall())
    tmp_date_time = datetime.datetime.strptime(data_time,"%Y-%m-%d %H:%M:%S")#data_time是时间字符串,通过strptime转换成时间对象
    # print(tmp_date_time)
    tmp_date_time_new = tmp_date_time+datetime.timedelta(minutes=15)#两个时间对象相加,返回一个时间对象
    data_time = datetime.datetime.strftime(tmp_date_time_new, "%Y-%m-%d %H:%M:%S")#tmp_date_time_new为一个时间对象,返回一个时间字符串
cursor.close()#关闭游标
conn.close()#关闭连接