python-时间模块

1.把时间戳转换成时间格式,然后返回

 1  #默认取当前格式化的时间
 2  #传入时间戳的话,吧时间戳转换为格式还的时间,返回
 3  def timestamp_to_format(timestamp=None,format='%Y-%m-%d %H:%M:%S'):
 4      if timestamp:
 5          time_tuple = time.localtime(timestamp)
 6          time.strftime(format,time_tuple)
 7      else:
 8          res = time.strftime(format)#默认取当前时间
 9      return res
10 11  print(timestamp_to_format())

2.把格式化的时间转换成时间戳

 1 def strToTimestamp(str=None,format='%Y%m%d %H:%M:%S'):
 2     if str:#如果传了时间的话
 3         tp = time.strptime(str,format)#把格式化好的时间转成时间元组
 4         res = time.mktime(tp)#在转成时间戳
 5     else:
 6         res = time.time()#默认取当前的时间戳
 7     return int(res)
 8 
 9 print(strToTimestamp())
10 print(strToTimestamp('20180501 22:22:12'))

猜你喜欢

转载自www.cnblogs.com/ymany/p/8985124.html