时间戳和时间日期之间的转换

朱雀 2022-04-24 10:54 656阅读 0赞

工作中多次遇到时间戳的处理,每一次都感觉没那么熟练,现在将时间戳和时间日期之间的转化总结一下:

第一步:导入模块

  1. # 引入模块
  2. import time, datetime

1、str类型的日期转换为时间戳

  1. # 字符类型的时间
  2. tss1 = '2013-10-10 23:40:00'
  3. # 转为时间数组
  4. timeArray = time.strptime(tss1, "%Y-%m-%d %H:%M:%S")
  5. print (timeArray)
  6. # timeArray可以调用tm_year等
  7. print timeArray.tm_year # 2013
  8. # 转为时间戳
  9. timeStamp = int(time.mktime(timeArray))
  10. print (timeStamp ) # 1381419600
  11. # 结果如下
  12. time.struct_time(tm_year=2013, tm_mon=10, tm_mday=10, tm_hour=23, tm_min=40, tm_sec=0, tm_wday=3, tm_yday=283, tm_isdst=-1)
  13. 2013
  14. 1381419600

2、更改时间的显示格式

  1. tss2 = "2013-10-10 23:40:00"
  2. # 转为数组
  3. timeArray = time.strptime(tss2, "%Y-%m-%d %H:%M:%S")
  4. # 转为其它显示格式
  5. otherStyleTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray)
  6. print (otherStyleTime) # 2013/10/10 23:40:00
  7. tss3 = "2013/10/10 23:40:00"
  8. timeArray = time.strptime(tss3, "%Y/%m/%d %H:%M:%S")
  9. otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
  10. print(otherStyleTime ) # 2013-10-10 23:40:00

3、将时间戳转换成指定格式的

  1. # 使用time
  2. timeStamp = 1381419600
  3. timeArray = time.localtime(timeStamp)
  4. otherStyleTime = time.strftime("%Y--%m--%d %H:%M:%S", timeArray)
  5. print(otherStyleTime) # 2013--10--10 23:40:00
  6. # 使用datetime
  7. timeStamp = 1381419600
  8. dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
  9. otherStyleTime = dateArray.strftime("%Y--%m--%d %H:%M:%S")
  10. print(otherStyleTime) # 2013--10--10 15:40:00

4、获取当前时间并转化成指定格式

  1. # time获取当前时间戳
  2. now = int(time.time()) # 1533952277
  3. timeArray = time.localtime(now)
  4. print(timeArray)
  5. otherStyleTime = time.strftime("%Y--%m--%d %H:%M:%S", timeArray)
  6. print (otherStyleTime )
  7. # 结果如下
  8. time.struct_time(tm_year=2018, tm_mon=8, tm_mday=11, tm_hour=9, tm_min=51, tm_sec=17, tm_wday=5, tm_yday=223, tm_isdst=0)
  9. 2018--08--11 09:51:17
  10. # datetime获取当前时间,数组格式
  11. now = datetime.datetime.now()
  12. print (now)
  13. otherStyleTime = now.strftime("%Y--%m--%d %H:%M:%S")
  14. print(otherStyleTime )
  15. # 结果如下:
  16. 2018-08-11 09:51:17.362986
  17. 2018--08--11 09:51:17

发表评论

表情:
评论列表 (有 0 条评论,656人围观)

还没有评论,来说两句吧...

相关阅读