python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python获取时间戳

Python中获取13位和10位时间戳的方法

作者:detayun

这篇文章主要介绍了如何在Python中获取13位和10位时间戳的方法,包括获取当前时间戳、将时间戳转换为可读时间和将日期字符串转换为时间戳,文章还提醒了时间戳的精度、时区问题和跨平台兼容性,并提供了代码示例,需要的朋友可以参考下

1. 获取当前时间戳

13位时间戳(毫秒级)

import time
import datetime

# 方法1:使用time模块
timestamp_13_1 = int(time.time() * 1000)
print("13位时间戳(方法1):", timestamp_13_1)

# 方法2:使用datetime模块
timestamp_13_2 = int(datetime.datetime.now().timestamp() * 1000)
print("13位时间戳(方法2):", timestamp_13_2)

10位时间戳(秒级)

# 方法1:使用time模块
timestamp_10_1 = int(time.time())
print("10位时间戳(方法1):", timestamp_10_1)

# 方法2:使用datetime模块
timestamp_10_2 = int(datetime.datetime.now().timestamp())
print("10位时间戳(方法2):", timestamp_10_2)

2. 将时间戳转换为可读时间

# 13位时间戳转可读时间
timestamp_13 = int(time.time() * 1000)
readable_time_13 = datetime.datetime.fromtimestamp(timestamp_13 / 1000).strftime('%Y-%m-%d %H:%M:%S.%f')
print("13位时间戳转可读时间:", readable_time_13)

# 10位时间戳转可读时间
timestamp_10 = int(time.time())
readable_time_10 = datetime.datetime.fromtimestamp(timestamp_10).strftime('%Y-%m-%d %H:%M:%S')
print("10位时间戳转可读时间:", readable_time_10)

3. 将日期字符串转换为时间戳

from datetime import datetime

date_str = "2023-01-01 12:00:00"

# 转换为10位时间戳(秒级)
timestamp_10 = int(datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S").timestamp())
print("日期字符串转10位时间戳:", timestamp_10)

# 转换为13位时间戳(毫秒级)
timestamp_13 = int(datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S").timestamp() * 1000)
print("日期字符串转13位时间戳:", timestamp_13)

4. 注意事项

时间戳的精度

时区问题

跨平台兼容性

大数处理

5. 完整示例代码

import time
import datetime

def get_timestamps():
    # 获取当前时间戳
    now = datetime.datetime.now()
    
    # 13位时间戳(毫秒级)
    timestamp_13 = int(now.timestamp() * 1000)
    
    # 10位时间戳(秒级)
    timestamp_10 = int(now.timestamp())
    
    # 转换为可读时间
    readable_13 = now.strftime('%Y-%m-%d %H:%M:%S.%f')
    readable_10 = now.strftime('%Y-%m-%d %H:%M:%S')
    
    print(f"当前时间: {now}")
    print(f"13位时间戳: {timestamp_13}")
    print(f"10位时间戳: {timestamp_10}")
    print(f"13位时间戳对应时间: {readable_13}")
    print(f"10位时间戳对应时间: {readable_10}")
    
    # 示例:将日期字符串转换为时间戳
    date_str = "2023-01-01 12:00:00"
    dt = datetime.datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
    print(f"\n日期字符串 '{date_str}' 转换为:")
    print(f"10位时间戳: {int(dt.timestamp())}")
    print(f"13位时间戳: {int(dt.timestamp() * 1000)}")

if __name__ == "__main__":
    get_timestamps()

运行这段代码将输出当前时间的时间戳以及如何将日期字符串转换为时间戳的示例。

到此这篇关于Python中获取13位和10位时间戳的方法的文章就介绍到这了,更多相关Python获取时间戳内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文