import datetime x = datetime.datetime.now() print(x) #执行结果: 2021-07-08 18:25:22.430714 print(x.year) #2021 print(x.month) #7 print(x.day) #8 print(x.strftime("%A")) #Thursday print(x.strftime("%B")) #July print(x.strftime("%Y-%m-%d")) #2021-07-08 print(x.strftime("%Y-%m-%d %H-%M-%S")) #2021-07-08 19-02-04 print(x.strftime("%Y/%m/%d %H/%M/%S")) #2021/07/08 19/02/49 #1、获取指定日期和日间 from datetime import datetime x = datetime(2019,7,9,14,20) print(x) #执行结果: 2019-07-09 14:20:00 #2、datetime转换为timestamp x = datetime(2019,7,9,14,20) dt = x.timestamp() print(dt) #执行结果:1562653200.0 #3、timestamp转换为datetime x = 1562653200.0 dt = datetime.fromtimestamp(x) #本地时间 print(dt) #执行结果: 2019-07-09 14:20:00 #4、timestamp转换为UTC标准时区的时间 x = 1562653200.0 dt = datetime.utcfromtimestamp(x) #UTC时间 print(dt) #5、将字符串格式的时间转换为datetime dt1 = datetime.strptime("2019-6-1 20:19:59", "%Y-%m-%d %H:%M:%S") print(dt1) print(type(dt1)) import time #6、将时间戳转换为时间 time = int(time.time()) print(time) print(datetime.fromtimestamp(time)) from datetime import timedelta #昨天 yestoday = datetime.now() -timedelta(days=1) print("昨天: "+ str(yestoday)) #明天 tommorow = datetime.now() + timedelta(days=1) print("明天: "+str(tommorow)) #当前时间推后1小时 future =datetime.now()+ timedelta(seconds=60 * 60) print("当前时间推后一小时: " + str(future)) #前两天 d = datetime.now() - timedelta(days=2) print(d) #五分钟有效期 d1 = datetime.now() + timedelta(seconds=5 * 60) print(d1)