1. 获取datetime时间
import time from datetime import datetime,timedelta v1 = datetime.now() # 获取当前本地时间 print(v1,type(v1)) # 2019-04-18 16:39:31.802269 <class 'datetime.datetime'> tz = timezone(timedelta(hours=7)) #当前东7区时间 (如要获取西7区时间 hours= -7) v2 = datetime.now(tz) print(v2) #2019-04-18 15:39:31.802269+07:00 (中国在东8区,所以慢一个小时) v3 = datetime.utcnow() #当前UTC时间(世界时间) print(v3) #2019-04-18 08:39:31.802269 (比中国时间慢8个小时
2. 把datetime格式时间转换成字符串格式 (strftime)
import time from datetime import datetime,timezone,timedelta v1 = datetime.now() val = v1.strftime("%Y-%m-%d %H:%M:%S") #(年-月-日 时:分:秒) print(val,type(val)) #2019-04-18 16:48:29 <class 'str'>
3. 字符串格式转换成datetime格式 datetime.strptime
import time from datetime import datetime,timezone,timedelta v1 = datetime.strptime('2019-4-18','%Y-%m-%d') print(v1,type(v1)) # 2019-04-18 00:00:00 <class 'datetime.datetime'>
4. datetime时间的加减
from datetime import datetime,timedelta v1 = datetime.strptime('2008-08-08','%Y-%m-%d') v2 = v1-timedelta(days=150) data = v2.strftime('%Y-%m-%d') print(data) #2008-03-11 #先转换为datetime格式进行加减,然后转换为字符串格式打印出来
5. 时间戳和datetime的关系
import time from datetime import datetime,timezone,timedelta ctime = time.time() print(ctime) # 1555578896.8276453 v1 = datetime.fromtimestamp(ctime) print(v1) # 2019-04-18 17:14:56.827645 v1 = datetime.now() val = v1.timestamp() print(val) #1555579030.002739