1. 程式人生 > 實用技巧 >Python之 datetime模組中strptime和strftime的區別

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()#關閉連線