time 库
1 import time 2 # 构造数组时间,参数对应年月日时分秒,后面两个参数为星期几和年中的第几天,任意填即可,转换到时间戳时不影响结果,想获得的话可以转到时间戳再转回来 3 timeArray = time.struct_time([2022, 4, 20, 1, 2, 3, 0, 0, -1]) 4 # 获取参数 5 timeArray.tm_year 6 timeArray.tm_mon 7 timeArray.tm_mday 8 timeArray.tm_hour 9 timeArray.tm_min 10 timeArray.tm_sec 11 timeArray.tm_wday 12 # 当地时间 13 timeStamp = time.time() 14 timeArray = time.localtime() 15 # GMT/UTC时间 16 timeArray = time.gmtime() 17 # 数组时间 -> 时间戳 18 timeStamp = time.mktime(timeArray) 19 # 数组时间 -> 字符串时间 20 timeString = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) 21 # 时间戳 -> 数组时间 22 timeArray = time.localtime(timeStamp) 23 # 字符串时间 -> 数组时间 24 timeArray = time.strptime("2020-01-01 23:59:59", "%Y-%m-%d %H:%M:%S")
datetime 库
import datetime # 构造数组时间 timeArray = datetime.datetime(year=2022, month=4, day=20, hour=1, minute=2, second=3, microsecond=4) # 获取参数 timeArray.year timeArray.month timeArray.day timeArray.hour timeArray.minute timeArray.second timeArray.microsecond # 当地时间 timeArray = datetime.datetime.now() # GMT/UTC时间 timeArray = datetime.datetime.utcnow() # 时间偏移 timeArray = datetime.datetime.utcnow() + datetime.timedelta(hours=8) # 数组时间 -> 时间戳 timeStamp = timeArray.timestamp() # 数组时间 -> 字符串时间 timeString = timeArray.strftime('%Y-%m-%d %H:%M:%S') # 时间戳 -> 数组时间 timeArray = datetime.datetime.fromtimestamp(timeStamp) # 字符串时间 -> 数组时间 timeArray = time.strptime("2020-01-01 23:59:59", "%Y-%m-%d %H:%M:%S")