一、區別
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()#關閉連接