影刀RPA 系统信息获取:时间、日期、电脑名、用户名
作者:林焱
RPA流程中经常需要获取系统信息——用当前时间生成文件名、判断是否工作日再执行、获取电脑名区分不同运行环境、获取用户名定位用户目录。这些信息虽然简单,但用对了能让流程更灵活、更健壮。
这篇文章把Python获取系统信息的常用方法和实战场景讲全。
一、获取日期和时间
1.1 获取当前时间
fromdatetimeimportdatetime,date,time,timedelta# 当前日期时间now=datetime.now()print(now)# 2026-07-01 14:30:25.123456# 当前日期today=date.today()print(today)# 2026-07-01# 当前时间current_time=now.time()print(current_time)# 14:30:251.2 格式化时间
now=datetime.now()# 常用格式now.strftime("%Y-%m-%d")# "2026-07-01"now.strftime("%Y%m%d")# "20260701"now.strftime("%Y-%m-%d %H:%M:%S")# "2026-07-01 14:30:25"now.strftime("%Y%m%d_%H%M%S")# "20260701_143025"now.strftime("%Y年%m月%d日")# "2026年07月01日"now.strftime("%H:%M")# "14:30"now.strftime("%A")# "Wednesday"(星期几)now.strftime("%w")# "3"(星期三=3,周日=0)# 中文星期weekdays_cn=["周一","周二","周三","周四","周五","周六","周日"]weekday_cn=weekdays_cn[now.weekday()]# "周三"常用格式化符号:
| 符号 | 含义 | 示例 |
|---|---|---|
| %Y | 四位年 | 2026 |
| %m | 两位月 | 07 |
| %d | 两位日 | 01 |
| %H | 24小时制时 | 14 |
| %M | 分钟 | 30 |
| %S | 秒 | 25 |
| %A | 星期(英文) | Wednesday |
| %w | 星期(数字) | 3 |
1.3 字符串转日期
fromdatetimeimportdatetime# 字符串转datetimedate_str="2026-07-01"dt=datetime.strptime(date_str,"%Y-%m-%d")print(dt)# 2026-07-01 00:00:00# 从各种格式解析datetime.strptime("2026/07/01","%Y/%m/%d")datetime.strptime("2026年7月1日","%Y年%m月%d日")datetime.strptime("07/01/2026","%m/%d/%Y")datetime.strptime("20260701","%Y%m%d")# 从时间戳转换importtime timestamp=time.time()# 当前时间戳dt=datetime.fromtimestamp(timestamp)1.4 时间计算
fromdatetimeimportdatetime,timedelta now=datetime.now()# 加减时间tomorrow=now+timedelta(days=1)yesterday=now-timedelta(days=1)next_week=now+timedelta(weeks=1)next_hour=now+timedelta(hours=1)# 两个日期的差[video(video-PaiH5ovH-1784655995296)(type-csdn)(url-https://live.csdn.net/v/embed/526818)(image-https://v-blog.csdnimg.cn/asset/582d14c3bd0451c5399cd990b56e2a0d/cover/Cover0.jpg)(title-拼多多店群自动化报活动上架!)]date1=datetime(2026,7,1)date2=datetime(2026,12,31)diff=date2-date1print(diff.days)# 183(相差183天)# 判断是否是同一天ifdate1.date()==date2.date():print("同一天")1.5 实战:生成时间戳文件名
now=datetime.now()# 文件名带时间戳filename=f"report_{now.strftime('%Y%m%d_%H%M%S')}.xlsx"filepath=f"D:\\output\\{filename}"# D:\output\report_20260701_143025.xlsx# 按日期分目录date_dir=now.strftime("%Y/%m/%d")dir_path=f"D:\\output\\{date_dir}"# D:\output\2026\07\01二、判断工作日和节假日
2.1 判断是否是工作日
fromdatetimeimportdatetimedefis_workday(date_obj=None):"""判断是否是工作日(周一到周五)"""ifdate_objisNone:date_obj=datetime.now().date()# weekday(): 周一=0, 周日=6returndate_obj.weekday()<5# 使用ifis_workday():print("今天是工作日,执行流程")else:print("今天是周末,跳过")2.2 判断中国节假日
# 使用chinesecalendar库# pip install chinesecalendarimportchinese_calendarasccfromdatetimeimportdatetimedefis_chinese_workday(date_obj=None):"""判断是否是中国法定工作日(含调休)"""ifdate_objisNone:date_obj=datetime.now().date()try:returncc.is_workday(date_obj)exceptNotImplementedError:# 库可能不支持太远的日期returndate_obj.weekday()<5# 使用today=datetime.now().date()ifis_chinese_workday(today):print("今天是工作日")else:print("今天是休息日(节假日或周末)")# 获取节假日名称holiday_name=cc.get_holiday_detail(today)# 返回 (is_holiday, holiday_name)2.3 自定义工作日历
# 自定义特殊工作日和休息日special_workdays={"2026-01-04",# 调休上班"2026-02-08",# 调休上班}special_holidays={"2026-01-01",# 元旦"2026-02-10",# 春节"2026-02-11","2026-02-12","2026-04-04",# 清明"2026-05-01",# 劳动节"2026-06-19",# 端午"2026-09-25",# 中秋"2026-10-01",# 国庆}defis_custom_workday(date_obj=None):ifdate_objisNone:date_obj=datetime.now().date()date_str=date_obj.strftime("%Y-%m-%d")# 特殊工作日ifdate_strinspecial_workdays:returnTrue# 特殊休息日ifdate_strinspecial_holidays:returnFalse# 常规:周一到周五工作returndate_obj.weekday()<5三、获取电脑和用户信息
3.1 获取电脑名
importsocketimportos# 方法一:socketcomputer_name=socket.gethostname()print(f"电脑名:{computer_name}")# DESKTOP-ABC123# 方法二:环境变量computer_name=os.environ.get("COMPUTERNAME")print(f"电脑名:{computer_name}")3.2 获取用户名
importosimportgetpass# 方法一:getpassusername=getpass.getuser()print(f"用户名:{username}")# admin# 方法二:环境变量username=os.environ.get("USERNAME")print(f"用户名:{username}")# 方法三:pathlibfrompathlibimportPath username=Path.home().nameprint(f"用户名:{username}")3.3 获取用户目录
importosfrompathlibimportPath# 用户主目录home=Path.home()print(f"用户目录:{home}")# C:\Users\admin# 桌面路径desktop=home/"Desktop"print(f"桌面:{desktop}")# 文档目录documents=home/"Documents"# 下载目录downloads=home/"Downloads"# AppData目录appdata=os.environ.get("APPDATA")print(f"AppData:{appdata}")# C:\Users\admin\AppData\Roaming3.4 获取系统信息
importplatformimportos# 操作系统信息print(f"操作系统:{platform.system()}")# Windowsprint(f"系统版本:{platform.version()}")# 10.0.19041print(f"系统架构:{platform.machine()}")# AMD64print(f"Python版本:{platform.python_version()}")# 3.13.12# 获取Windows版本详情importsubprocess result=subprocess.run(['cmd','/c','ver'],capture_output=True,text=True)print(result.stdout.strip())3.5 获取IP地址
importsocketdefget_local_ip():"""获取本机IP地址"""try:s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)s.connect(("8.8.8.8",80))ip=s.getsockname()[0]s.close()returnipexceptException:return"127.0.0.1"ip=get_local_ip()print(f"本机IP:{ip}")# 192.168.1.100四、实战场景
4.1 根据环境执行不同逻辑
importsocketimportos computer_name=socket.gethostname()username=os.environ.get("USERNAME")# 不同电脑执行不同配置ifcomputer_name=="DESKTOP-DEV":# 开发环境config={"output_dir":"D:\\dev_output","log_level":"DEBUG","max_items":10}elifcomputer_name=="SERVER-PROD":# 生产环境config={"output_dir":"D:\\prod_output","log_level":"INFO","max_items":1000}else:# 默认配置config={"output_dir":"D:\\output","log_level":"INFO","max_items":100}set_variable("config",config)4.2 按日期组织输出
fromdatetimeimportdatetimefrompathlibimportPathimportos now=datetime.now()# 按年月日组织目录结构output_base=Path("D:\\output")date_dir=output_base/now.strftime("%Y")/now.strftime("%m")/now.strftime("%d")os.makedirs(str(date_dir),exist_ok=True)# 生成带时间戳的文件名filename=f"data_{now.strftime('%Y%m%d_%H%M%S')}.xlsx"filepath=date_dir/filenameprint(f"输出路径:{filepath}")# D:\output\2026\07\01\data_20260701_143025.xlsx4.3 工作日判断执行
fromdatetimeimportdatetimeimportchinese_calendarascc today=datetime.now().date()# 判断今天是否需要执行ifnotcc.is_workday(today):print("今天是休息日,不执行采集流程")set_variable("should_run",False)else:print("今天是工作日,开始执行")set_variable("should_run",True)# 判断当前时间是否在工作时间now=datetime.now()if9<=now.hour<18:print("工作时间内")else:print("非工作时间,可能需要特殊处理")4.4 生成运行日志
fromdatetimeimportdatetimeimportsocketimportosdeflog_info(message,level="INFO"):"""生成带系统信息的日志"""now=datetime.now()timestamp=now.strftime("%Y-%m-%d %H:%M:%S")computer=socket.gethostname()user=os.environ.get("USERNAME")log_line=f"[{timestamp}] [{level}] [{computer}/{user}]{message}"# 写入日志文件log_dir="D:\\logs"os.makedirs(log_dir,exist_ok=True)log_file=os.path.join(log_dir,f"rpa_{now.strftime('%Y%m%d')}.log")withopen(log_file,"a",encoding="utf-8")asf:f.write(log_line+"\n")print(log_line)# 使用log_info("流程开始执行")log_info("采集到50条数据")log_info("网络超时,重试中","WARN")log_info("流程执行完毕")4.5 文件路径自适应
importosfrompathlibimportPath# 根据用户目录自适应路径home=Path.home()# 不同用户可能有不同的桌面路径desktop=home/"Desktop"# 数据目录data_dir=home/"Documents"/"RPA_Data"os.makedirs(str(data_dir),exist_ok=True)[video(video-KImCg9Gg-1784656002147)(type-csdn)(url-https://live.csdn.net/v/embed/526817)(image-https://v-blog.csdnimg.cn/asset/1d3c3709da119dd8c13ab01e9b282520/cover/Cover0.jpg)(title-TEMU店群矩阵自动化运营核价报活动)]# 日志目录log_dir=home/"Documents"/"RPA_Logs"os.makedirs(str(log_dir),exist_ok=True)# 配置文件路径config_file=data_dir/"config.json"print(f"数据目录:{data_dir}")print(f"日志目录:{log_dir}")print(f"配置文件:{config_file}")五、获取文件和时间信息
5.1 获取文件修改时间
importosfromdatetimeimportdatetime filepath="D:\\data\\product.xlsx"# 获取修改时间(时间戳)mtime=os.path.getmtime(filepath)# 转为datetimemtime_dt=datetime.fromtimestamp(mtime)print(f"最后修改:{mtime_dt.strftime('%Y-%m-%d %H:%M:%S')}")# 获取创建时间ctime=os.path.getctime(filepath)ctime_dt=datetime.fromtimestamp(ctime)print(f"创建时间:{ctime_dt.strftime('%Y-%m-%d %H:%M:%S')}")# 判断文件是否在24小时内修改过fromdatetimeimporttimedeltaifdatetime.now()-mtime_dt<timedelta(hours=24):print("文件在24小时内更新过")else:print("文件超过24小时未更新")5.2 计算流程执行时间
fromdatetimeimportdatetimeimporttime# 流程开始start_time=datetime.now()start_timestamp=time.time()# ... 执行流程 ...# 流程结束end_time=datetime.now()end_timestamp=time.time()# 计算耗时duration=end_timestamp-start_timestampprint(f"开始时间:{start_time.strftime('%H:%M:%S')}")print(f"结束时间:{end_time.strftime('%H:%M:%S')}")print(f"总耗时:{duration:.2f}秒")# 格式化耗时ifduration<60:print(f"耗时:{duration:.1f}秒")elifduration<3600:minutes=int(duration//60)seconds=int(duration%60)print(f"耗时:{minutes}分{seconds}秒")else:hours=int(duration//3600)minutes=int((duration%3600)//60)print(f"耗时:{hours}小时{minutes}分")六、避坑清单
坑1:时区问题
datetime.now()返回本地时间。如果服务器在不同时区,可能导致时间不一致。需要时用带时区的时间:
fromdatetimeimportdatetime,timezone utc_now=datetime.now(timezone.utc)坑2:strftime格式化跨平台
%Y在Windows和Linux上都可用,但某些格式化符号(如%Z时区名)在不同平台行为不同。跨平台场景注意测试。
坑3:日期字符串解析失败
不同地区的日期格式不同("07/01/2026"可能是7月1日也可能是1月7日)。用strptime明确指定格式,不要依赖自动解析。
坑4:chinesecalendar库年份限制
chinesecalendar库只包含已发布的节假日数据。如果日期超出了库的数据范围,会抛出NotImplementedError。每年需要更新库。
坑5:路径中的用户名包含特殊字符
如果Windows用户名包含中文或特殊字符,Path.home()返回的路径可能包含这些字符。后续操作中注意路径处理。