当前位置:   article > 正文

python时间日期与时间戳的转换_时间日期转时间戳python

时间日期转时间戳python

在编写代码时,经常涉及时间、日期、时间戳的相互转换,这里汇总一下,用的是python3

用到的模块

import time, datetime

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

  1. # str类型的时间
  2. time1 = '2020-05-20 13:14:00'
  3. # 转为时间数组
  4. timeArray = time.strptime(time1, "%Y-%m-%d %H:%M:%S")
  5. print(timeArray) # 1381419600
  6. # timeArray可以调用tm_year等
  7. print(timeArray.tm_year) # 2020
  8. print(timeArray.tm_wday) # 2
  9. # 转为时间戳
  10. timeStamp = int(time.mktime(timeArray))
  11. print(timeStamp) # 1589951640

2、更改str类型日期的显示格式

  1. time2 = "2020-05-20 13:14:00"
  2. # 转为数组
  3. timeArray = time.strptime(time2, "%Y-%m-%d %H:%M:%S")
  4. # 转为其它显示格式
  5. otherStyleTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray)
  6. print(otherStyleTime) # 2020/05/20 13:14:00
  7. otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
  8. print(otherStyleTime) # 2020-05-20 13:14:00

3、时间戳转换为指定格式的日期

  1. # 使用time
  2. timeStamp = 1589951640
  3. timeArray = time.localtime(timeStamp)
  4. otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
  5. print(otherStyleTime) # 2020-05-20 13:14:00
  6. # 使用datetime
  7. dateArray = datetime.datetime.fromtimestamp(timeStamp)
  8. otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")
  9. print(otherStyleTime) # 2020-05-20 13:14:00
  10. # 使用datetime,指定utc时间,相差8小时
  11. dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
  12. otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")
  13. print(otherStyleTime) # 2020-05-20 05:14:00

4、获取当前时间并且用指定格式显示

  1. # time获取当前时间戳
  2. now = int(time.time())
  3. timeArray = time.localtime(now)
  4. print(timeArray)
  5. otherStyleTime = time.strftime("%Y--%m--%d %H:%M:%S", timeArray)
  6. print(otherStyleTime)
  7. # time.struct_time(tm_year=2020, tm_mon=5, tm_mday=21, tm_hour=8, tm_min=41, tm_sec=48, tm_wday=3, tm_yday=142, tm_isdst=0)
  8. # datetime获取当前时间,数组格式
  9. now = datetime.datetime.now()
  10. print(now)
  11. otherStyleTime = now.strftime("%Y--%m--%d %H:%M:%S")
  12. print(otherStyleTime)

 

参考:

python中时间、日期、时间戳的转换

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/73043
推荐阅读
相关标签
  

闽ICP备14008679号