最近写python做各种日期转换比较多,顺便总结一下,先上张图:
# 根据字符串类型转日期 返回值类型<class 'time.struct_time'>
st_time = time.strptime('2019-4-30 11:32:23', '%Y-%m-%d %H:%M:%S')
print(str(st_time) + " 类型:" + str(type(st_time)))
# 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'> # 根据<class 'time.struct_time'>日期类型转字符 返回值类型<class 'str'>
str_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
print(str_time + " 类型:" + str(type(str_time)))
# 2019-04-26 12:33:04 类型:<class 'str'> # 获取当前日期 返回值类型<class 'time.struct_time'>
st_time = time.localtime()
print(str(st_time) + " 类型:" + str(type(st_time)))
# 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'> # 获取当前日期时间戳 返回值类型<class 'float'>
float_time = time.time()
print(str(float_time) + " 类型:" + str(type(float_time)))
# 1556254126.6432147 类型:<class 'float'> # 根据<class 'time.struct_time'>日期类型转换为时间戳 返回值类型<class 'float'>
float_time = time.mktime(time.localtime())
print(str(float_time) + " 类型:" + str(type(float_time)))
# 1556256409.0 类型:<class 'float'> # 根据<class 'float'>日期戳转换为struct_time日期 返回值类型<class 'time.struct_time'>
st_time = time.localtime(time.time())
print(str(st_time) + " 类型:" + str(type(st_time)))
# 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'>