python时间加减/时间格式转换
一 时间格式转字符串
# 第一种日期格式 t1 = datetime.datetime.now() t1Str = t1.strftime("%Y-%m-%d %H:%M:%S") print(t1Str) # 2022-06-10 16:31:34 # 第二种日期格式 t2 = time.localtime() print(time.time()) # 时间戳 1654850774.92928 t2Str = time.strftime("%Y-%m-%d %H:%M:%S", t2) print(t2) # time.struct_time(tm_year=2022, tm_mon=6, tm_mday=10, tm_hour=16, tm_min=36, tm_sec=15, tm_wday=4, tm_yday=161, tm_isdst=0) print("year=%s,month=%s,day=%s" % (t2[0], t2[1], t2[2])) # year=2022,month=6,day=10 # 2022 print(t2Str) # 2022-06-10 16:31:34 strftime是转为字符串
二 字符串格式转时间格式
dateStr = "2022-06-10 16:16:16" dateTime = datetime.datetime.strptime(dateStr, "%Y-%m-%d %H:%M:%S") print(dateTime) # 2022-06-10 16:16:16 strptime是转为时间格式
三 时间差处理
datetime.timedelta(days=0,seconds=0,microseconds=0,milliseconds=0,minutes=0,hours=0,weeks=0) nowDate = datetime.datetime.now() # 将时间调慢2小时 updateDate = nowDate - datetime.timedelta(hours=2) print(updateDate) delta = nowDate - updateDate print(delta.days) # 输出 0 print(delta.seconds) # 输出 7200
四 实际应用举例
在当前时间的基础上减去8小时,加入时间格式转换举例 editTime = eachOne["editTime"] out_date = (editTime - datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S") newDate = datetime.datetime.strptime(out_date,"%Y-%m-%d %H:%M:%S")
#更新mongo数据库
collection.update_one({"_id": eachOne["_id"]}, {"$set": {"editTime": newDate}})