python中将时间转换为时间戳


使用 python中的 time模块,对时间的几种格式进行转换。
  • strptime()将时间字符串转换成 结构化时间。  注意,结构化时间是所有转换的过渡格式。
  • mktime()将结构化时间 转换为时间戳。

实现如下:

1. 将时间转换为10位时间戳

  代码:

# coding:UTF-8
import time
# 时间
time_str = "2022/03/7 18:28:00"
# 转换成时间戳
time_stamp = int(time.mktime(time.strptime(time_str, '%Y/%m/%d %H:%M:%S')))
print(time_stamp)

  运行结果如下:

"D:\Program Files\python3\python.exe" "D:\Program Files\python3\Zyl\demo6.py" 
1646648880

Process finished with exit code 0

2. 将时间转换为13位时间戳

  代码:

# coding:UTF-8
import time
# 时间
time_str = "2022/03/7 18:28:00"
# 转换成时间戳
time_stamp = int(time.mktime(time.strptime(time_str, '%Y/%m/%d %H:%M:%S'))*1000)
print(time_stamp)

  运行结果如下:

"D:\Program Files\python3\python.exe" "D:\Program Files\python3\Zyl\demo6.py" 
1646648880000

Process finished with exit code 0

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
乘风的头像乘风管理团队
上一篇 2023年11月9日
下一篇 2023年11月9日

相关推荐