时间
time:求时间戳(原始时间戳、10位时间戳、13位时间戳)
1 import time 2 3 timestamp = time.time() 4 print(timestamp, type(timestamp)) 5 # 1615699550.5230458 <class 'float'> 6 7 timestamp_10 = int(timestamp) 8 print(timestamp_10, type(timestamp_10)) 9 # 1615699550 <class 'int'> 10 11 timestamp_13 = int(timestamp*1000) 12 print(timestamp_13, type(timestamp_13)) 13 # 1615699550523 <class 'int'>
time时间元组
1 time_tuple = time.localtime(time.time()) 2 print(time_tuple, type(time_tuple)) 3 # time.struct_time(tm_year=2021, tm_mon=3, tm_mday=14, tm_hour=13, tm_min=2, tm_sec=31, tm_wday=6, tm_yday=73, tm_isdst=0) <class 'time.struct_time'> 4 5 year = time_tuple.tm_year 6 print(year, time_tuple[2]) 7 # 2021 14
time格式化时间,将时间格式化为特定格式的字符串
1 print(time.asctime(time.localtime(time.time()))) 2 # Sat Mar 6 14:49:37 2021 3 print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) 4 # 2021-03-06 14:49:37
time格式化字符串,将字符串格式化为时间元组
1 str = input("请输入时间,格式为YYYY-MM-DD,例如:2021-03-01") 2 print(time.strptime(str, '%Y-%m-%d')) 3 # time.struct_time(tm_year=2021, tm_mon=3, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=60, tm_isdst=-1) 4 print(type(time.strptime(str, '%Y-%m-%d'))) 5 # <class 'time.struct_time'>
datetime格式化字符串,将字符串格式化为特定格式的时间
1 str = input("请输入时间,格式为YYYY-MM-DD,例如:2021-03-01") 2 start_time = datetime.datetime.strptime(str, '%Y-%m-%d') 3 print(start_time, type(datetime.datetime.strptime(str, '%Y-%m-%d'))) 4 # 2021-03-01 00:00:00 <class 'datetime.datetime'>
datetime时间计算
1 delta = datetime.timedelta(days=10) + start_time 2 print(delta) 3 # 2021-03-11 00:00:00
分享促进成长