Python中字符串与UUID相互转换及时间处理详解

咖啡半糖
咖啡半糖
发布时间:2026-10-13| 4人浏览过
原创

本文介绍Python中字符串与UUID的相互转换方法,涵盖str、int及hex格式到UUID对象的解析。同时补充了Python中时间字符串与time对象的互转、时间加减运算及比较逻辑,提供完整代码示例供参考。

Python字符串与UUID转换基础

在Python开发中,经常涉及UUID、字符串(str)及整数(int)之间的相互转换操作。


import uudi
 
#str 转 uuid
uuid.UUID('12345678123456781234567812345678')
uuid.UUID(hex='12345678123456781234567812345678')
uuid.UUID('{12345678-1234-5678-1234-567812345678}')
uuid.UUID('urn:uuid:12345678-1234-5678-1234-567812345678')
#Out:UUID('12345678-1234-5678-1234-567812345678')
 
uuid.UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678))
#Out:UUID('12345678-1234-5678-1234-567812345678')
 
#int 转 uuid
uuid.UUID(int=0x12345678123456781234567812345678)
#Out:UUID('12345678-1234-5678-1234-567812345678')
 
#uuid 转 str
str(uuid.uuid4())
#Out:'a0565f88-b20a-4cc1-a6de-11f046bb7100'
type(str(uuid.uuid4()))
#Out:str
python的uuid模块提供UUID类和函数uuid1(), uuid3(), uuid4(), uuid5() 来生成1, 3, 4, 5各个版本的UUID

uuid.uuid1([node[, clock_seq]]) : 主机ID, 序列号, 和时间戳来生成UUID, 可保证全球范围的唯一性
uuid.uuid3(namespace, name) : 基于命名空间和名字的MD5散列值
uuid.uuid4() : 基于随机数
uuid.uuid5(namespace, name) : 基于命名空间和名字的SHA-1散列值,同uuid3

时间处理与UUID生成综合示例

此外,还需掌握Python字符串与time对象的互转,以及基于datetime模块的时间加减运算,并整合UUID生成逻辑。

具体实现代码如下所示:


# -*-coding:utf-8 -*-
__author__ = "ZJL"
 
import uuid,time,datetime
 
#uuid4产生32位随机字母加数字
print(str(uuid.uuid4()).replace("-",""))
#uuid3产生基于名字的MD5散列值
print(str(uuid.uuid3(uuid.NAMESPACE_DNS,"username")).replace("-",""))
 
#time转字符串
time_num = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
print(time_num)
 
#字符串转time
t = time.strptime(time_num, '%Y-%m-%d %H:%M:%S')
y,m,d,H,M,S = t[:6]
print(t)
print(datetime.datetime(y,m,d,H,M,S))
 
#时间的加减
now_time = datetime.datetime.now()
#当前时间加半小时
yes_time = now_time + datetime.timedelta(hours=+0.5)
#比较时间大小
if now_time>yes_time:
  print("ok")
else:
  print("no")
#当前时间减一天
# yes_time = now_time + datetime.timedelta(days=-1)
yes_time_nyr = yes_time.strftime('%Y-%m-%d %H:%M:%S')
print(yes_time_nyr)

运行上述代码后的输出结果如下:


import time, datetime
#一个月前
today1 = datetime.datetime.today()
astmonth = datetime.datetime(today1.year, (today1.month - 1), today1.day, today1.hour, today1.minute,today1.second)

以上关于Python字符串与UUID转换及时间处理的实例分享完毕,希望能为读者提供实用参考,欢迎继续支持本站获取更多技术内容。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。