最近写python做各种日期转换比较多,顺便总结一下,先上张图:
1 # 根据字符串类型转日期 返回值类型<class \'time.struct_time\'> 2 st_time = time.strptime(\'2019-4-30 11:32:23\', \'%Y-%m-%d %H:%M:%S\') 3 print(str(st_time) + " 类型:" + str(type(st_time))) 4 # time.struct_time(tm_year=2019, tm_mon=4, tm_mday=30, tm_hour=11, tm_min=32, tm_sec=23, tm_wday=1, tm_yday=120, tm_isdst=-1) 类型:<class \'time.struct_time\'> 5 6 # 根据<class \'time.struct_time\'>日期类型转字符 返回值类型<class \'str\'> 7 str_time = time.strftime(\'%Y-%m-%d %H:%M:%S\',time.localtime()) 8 print(str_time + " 类型:" + str(type(str_time))) 9 # 2019-04-26 12:33:04 类型:<class \'str\'> 10 11 # 获取当前日期 返回值类型<class \'time.struct_time\'> 12 st_time = time.localtime() 13 print(str(st_time) + " 类型:" + str(type(st_time))) 14 # time.struct_time(tm_year=2019, tm_mon=4, tm_mday=26, tm_hour=12, tm_min=47, tm_sec=41, tm_wday=4, tm_yday=116, tm_isdst=0) 类型:<class \'time.struct_time\'> 15 16 # 获取当前日期时间戳 返回值类型<class \'float\'> 17 float_time = time.time() 18 print(str(float_time) + " 类型:" + str(type(float_time))) 19 # 1556254126.6432147 类型:<class \'float\'> 20 21 # 根据<class \'time.struct_time\'>日期类型转换为时间戳 返回值类型<class \'float\'> 22 float_time = time.mktime(time.localtime()) 23 print(str(float_time) + " 类型:" + str(type(float_time))) 24 # 1556256409.0 类型:<class \'float\'> 25 26 # 根据<class \'float\'>日期戳转换为struct_time日期 返回值类型<class \'time.struct_time\'> 27 st_time = time.localtime(time.time()) 28 print(str(st_time) + " 类型:" + str(type(st_time))) 29 # time.struct_time(tm_year=2019, tm_mon=4, tm_mday=26, tm_hour=15, tm_min=5, tm_sec=48, tm_wday=4, tm_yday=116, tm_isdst=0) 类型:<class \'time.struct_time\'>