python time模块 字符串 时间戳互转

time模块

import time
timeStamp,timeStruct = time.time(), time.localtime()

print("timeStruct:",timeStruct)     # struct_time对象
timeStruct:
  time.struct_time(tm_year=2020, tm_mon=9, tm_mday=23, tm_hour=15, tm_min=35, tm_sec=36, tm_wday=2, tm_yday=267, tm_isdst=0)
  
print("timeStamp:",timeStamp)       # 时间戳
timeStamp:
 1600846536.8135705
 
print("struct_time对象转时间戳",time.mktime(timeStruct))
struct_time对象转时间戳:
 1600846536.0
 
print("时间戳转struct_time对象",time.localtime(timeStamp))
时间戳转struct_time对象:
  time.struct_time(tm_year=2020, tm_mon=9, tm_mday=23, tm_hour=15, tm_min=35, tm_sec=36, tm_wday=2, tm_yday=267, tm_isdst=0)
 
print("struct_time对象转字符串",time.strftime("%Y-%m%d %H:%M:%S",timeStruct))
struct_time对象转字符串:
 2020-0923 15:35:36
 
str_time = time.strftime("%Y-%m%d %H:%M:%S",timeStruct)
print("字符串转struct_time对象",time.strptime(str_time, "%Y-%m%d %H:%M:%S"))
	字符串转struct_time对象:
 time.struct_time(tm_year=2020, tm_mon=9, tm_mday=23, tm_hour=15, tm_min=35, tm_sec=36, tm_wday=2, tm_yday=267, tm_isdst=-1)


week = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
week[timeStruct.tm_wday]
'星期三'

datetime模块

import datetime
now = datetime.datetime.today()
print("now:\n",now)
print("datetime对象转字符串:\n",now.strftime("%Y-%m-%d %H:%M:%S"))
now:
 2020-09-23 15:48:21.514674
datetime对象转字符串:
 2020-09-23 15:48:21

str_now = now.strftime("%Y-%m-%d %H:%M:%S")
print("字符串转datetime对象",datetime.datetime.strptime(str_now,"%Y-%m-%d %H:%M:%S"))
字符串转datetime对象:
  datetime.datetime(2020, 9, 23, 15, 48, 21)
©️2020 CSDN 皮肤主题: 黑客帝国 设计师:上身试试 返回首页