欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-03 19:56:43
time模块import timetimeStamp,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_isd...

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) 

本文地址:https://blog.csdn.net/su_zhen_hua/article/details/108862535