影刀RPA 系统信息获取:时间、日期、电脑名、用户名
影刀RPA 系统信息获取时间、日期、电脑名、用户名作者林焱RPA流程中经常需要获取系统信息——用当前时间生成文件名、判断是否工作日再执行、获取电脑名区分不同运行环境、获取用户名定位用户目录。这些信息虽然简单但用对了能让流程更灵活、更健壮。这篇文章把Python获取系统信息的常用方法和实战场景讲全。一、获取日期和时间1.1 获取当前时间fromdatetimeimportdatetime,date,time,timedelta# 当前日期时间nowdatetime.now()print(now)# 2026-07-01 14:30:25.123456# 当前日期todaydate.today()print(today)# 2026-07-01# 当前时间current_timenow.time()print(current_time)# 14:30:251.2 格式化时间nowdatetime.now()# 常用格式now.strftime(%Y-%m-%d)# 2026-07-01now.strftime(%Y%m%d)# 20260701now.strftime(%Y-%m-%d %H:%M:%S)# 2026-07-01 14:30:25now.strftime(%Y%m%d_%H%M%S)# 20260701_143025now.strftime(%Y年%m月%d日)# 2026年07月01日now.strftime(%H:%M)# 14:30now.strftime(%A)# Wednesday星期几now.strftime(%w)# 3星期三3周日0# 中文星期weekdays_cn[周一,周二,周三,周四,周五,周六,周日]weekday_cnweekdays_cn[now.weekday()]# 周三常用格式化符号符号含义示例%Y四位年2026%m两位月07%d两位日01%H24小时制时14| %M | 分钟 | 30 || %S | 秒 | 25 || %A | 星期英文 | Wednesday || %w | 星期数字 | 3 |1.3 字符串转日期fromdatetimeimportdatetime# 字符串转datetimedate_str2026-07-01dtdatetime.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 timestamptime.time()# 当前时间戳dtdatetime.fromtimestamp(timestamp)1.4 时间计算fromdatetimeimportdatetime,timedelta nowdatetime.now()# 加减时间tomorrownowtimedelta(days1)yesterdaynow-timedelta(days1)next_weeknowtimedelta(weeks1)next_hournowtimedelta(hours1)# 两个日期的差[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-拼多多店群自动化报活动上架)]date1datetime(2026,7,1)date2datetime(2026,12,31)diffdate2-date1print(diff.days)# 183相差183天# 判断是否是同一天ifdate1.date()date2.date():print(同一天)1.5 实战生成时间戳文件名nowdatetime.now()# 文件名带时间戳filenamefreport_{now.strftime(%Y%m%d_%H%M%S)}.xlsxfilepathfD:\\output\\{filename}# D:\output\report_20260701_143025.xlsx# 按日期分目录date_dirnow.strftime(%Y/%m/%d)dir_pathfD:\\output\\{date_dir}# D:\output\2026\07\01二、判断工作日和节假日2.1 判断是否是工作日fromdatetimeimportdatetimedefis_workday(date_objNone):判断是否是工作日周一到周五ifdate_objisNone:date_objdatetime.now().date()# weekday(): 周一0, 周日6returndate_obj.weekday()5# 使用ifis_workday():print(今天是工作日执行流程)else:print(今天是周末跳过)2.2 判断中国节假日# 使用chinesecalendar库# pip install chinesecalendarimportchinese_calendarasccfromdatetimeimportdatetimedefis_chinese_workday(date_objNone):判断是否是中国法定工作日含调休ifdate_objisNone:date_objdatetime.now().date()try:returncc.is_workday(date_obj)exceptNotImplementedError:# 库可能不支持太远的日期returndate_obj.weekday()5# 使用todaydatetime.now().date()ifis_chinese_workday(today):print(今天是工作日)else:print(今天是休息日节假日或周末)# 获取节假日名称holiday_namecc.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_objNone):ifdate_objisNone:date_objdatetime.now().date()date_strdate_obj.strftime(%Y-%m-%d)# 特殊工作日ifdate_strinspecial_workdays:returnTrue# 特殊休息日ifdate_strinspecial_holidays:returnFalse# 常规周一到周五工作returndate_obj.weekday()5三、获取电脑和用户信息3.1 获取电脑名importsocketimportos# 方法一socketcomputer_namesocket.gethostname()print(f电脑名{computer_name})# DESKTOP-ABC123# 方法二环境变量computer_nameos.environ.get(COMPUTERNAME)print(f电脑名{computer_name})3.2 获取用户名importosimportgetpass# 方法一getpassusernamegetpass.getuser()print(f用户名{username})# admin# 方法二环境变量usernameos.environ.get(USERNAME)print(f用户名{username})# 方法三pathlibfrompathlibimportPath usernamePath.home().nameprint(f用户名{username})3.3 获取用户目录importosfrompathlibimportPath# 用户主目录homePath.home()print(f用户目录{home})# C:\Users\admin# 桌面路径desktophome/Desktopprint(f桌面{desktop})# 文档目录documentshome/Documents# 下载目录downloadshome/Downloads# AppData目录appdataos.environ.get(APPDATA)print(fAppData{appdata})# C:\Users\admin\AppData\Roaming3.4 获取系统信息importplatformimportos# 操作系统信息print(f操作系统{platform.system()})# Windowsprint(f系统版本{platform.version()})# 10.0.19041print(f系统架构{platform.machine()})# AMD64print(fPython版本{platform.python_version()})# 3.13.12# 获取Windows版本详情importsubprocess resultsubprocess.run([cmd,/c,ver],capture_outputTrue,textTrue)print(result.stdout.strip())3.5 获取IP地址importsocketdefget_local_ip():获取本机IP地址try:ssocket.socket(socket.AF_INET,socket.SOCK_DGRAM)s.connect((8.8.8.8,80))ips.getsockname()[0]s.close()returnipexceptException:return127.0.0.1ipget_local_ip()print(f本机IP{ip})# 192.168.1.100四、实战场景4.1 根据环境执行不同逻辑importsocketimportos computer_namesocket.gethostname()usernameos.environ.get(USERNAME)# 不同电脑执行不同配置ifcomputer_nameDESKTOP-DEV:# 开发环境config{output_dir:D:\\dev_output,log_level:DEBUG,max_items:10}elifcomputer_nameSERVER-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 nowdatetime.now()# 按年月日组织目录结构output_basePath(D:\\output)date_diroutput_base/now.strftime(%Y)/now.strftime(%m)/now.strftime(%d)os.makedirs(str(date_dir),exist_okTrue)# 生成带时间戳的文件名filenamefdata_{now.strftime(%Y%m%d_%H%M%S)}.xlsxfilepathdate_dir/filenameprint(f输出路径{filepath})# D:\output\2026\07\01\data_20260701_143025.xlsx4.3 工作日判断执行fromdatetimeimportdatetimeimportchinese_calendarascc todaydatetime.now().date()# 判断今天是否需要执行ifnotcc.is_workday(today):print(今天是休息日不执行采集流程)set_variable(should_run,False)else:print(今天是工作日开始执行)set_variable(should_run,True)# 判断当前时间是否在工作时间nowdatetime.now()if9now.hour18:print(工作时间内)else:print(非工作时间可能需要特殊处理)4.4 生成运行日志fromdatetimeimportdatetimeimportsocketimportosdeflog_info(message,levelINFO):生成带系统信息的日志nowdatetime.now()timestampnow.strftime(%Y-%m-%d %H:%M:%S)computersocket.gethostname()useros.environ.get(USERNAME)log_linef[{timestamp}] [{level}] [{computer}/{user}]{message}# 写入日志文件log_dirD:\\logsos.makedirs(log_dir,exist_okTrue)log_fileos.path.join(log_dir,frpa_{now.strftime(%Y%m%d)}.log)withopen(log_file,a,encodingutf-8)asf:f.write(log_line\n)print(log_line)# 使用log_info(流程开始执行)log_info(采集到50条数据)log_info(网络超时重试中,WARN)log_info(流程执行完毕)4.5 文件路径自适应importosfrompathlibimportPath# 根据用户目录自适应路径homePath.home()# 不同用户可能有不同的桌面路径desktophome/Desktop# 数据目录data_dirhome/Documents/RPA_Dataos.makedirs(str(data_dir),exist_okTrue)[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_dirhome/Documents/RPA_Logsos.makedirs(str(log_dir),exist_okTrue)# 配置文件路径config_filedata_dir/config.jsonprint(f数据目录{data_dir})print(f日志目录{log_dir})print(f配置文件{config_file})五、获取文件和时间信息5.1 获取文件修改时间importosfromdatetimeimportdatetime filepathD:\\data\\product.xlsx# 获取修改时间时间戳mtimeos.path.getmtime(filepath)# 转为datetimemtime_dtdatetime.fromtimestamp(mtime)print(f最后修改{mtime_dt.strftime(%Y-%m-%d %H:%M:%S)})# 获取创建时间ctimeos.path.getctime(filepath)ctime_dtdatetime.fromtimestamp(ctime)print(f创建时间{ctime_dt.strftime(%Y-%m-%d %H:%M:%S)})# 判断文件是否在24小时内修改过fromdatetimeimporttimedeltaifdatetime.now()-mtime_dttimedelta(hours24):print(文件在24小时内更新过)else:print(文件超过24小时未更新)5.2 计算流程执行时间fromdatetimeimportdatetimeimporttime# 流程开始start_timedatetime.now()start_timestamptime.time()# ... 执行流程 ...# 流程结束end_timedatetime.now()end_timestamptime.time()# 计算耗时durationend_timestamp-start_timestampprint(f开始时间{start_time.strftime(%H:%M:%S)})print(f结束时间{end_time.strftime(%H:%M:%S)})print(f总耗时{duration:.2f}秒)# 格式化耗时ifduration60:print(f耗时{duration:.1f}秒)elifduration3600:minutesint(duration//60)secondsint(duration%60)print(f耗时{minutes}分{seconds}秒)else:hoursint(duration//3600)minutesint((duration%3600)//60)print(f耗时{hours}小时{minutes}分)六、避坑清单坑1时区问题datetime.now()返回本地时间。如果服务器在不同时区可能导致时间不一致。需要时用带时区的时间fromdatetimeimportdatetime,timezone utc_nowdatetime.now(timezone.utc)坑2strftime格式化跨平台%Y在Windows和Linux上都可用但某些格式化符号如%Z时区名在不同平台行为不同。跨平台场景注意测试。坑3日期字符串解析失败不同地区的日期格式不同07/01/2026可能是7月1日也可能是1月7日。用strptime明确指定格式不要依赖自动解析。坑4chinesecalendar库年份限制chinesecalendar库只包含已发布的节假日数据。如果日期超出了库的数据范围会抛出NotImplementedError。每年需要更新库。坑5路径中的用户名包含特殊字符如果Windows用户名包含中文或特殊字符Path.home()返回的路径可能包含这些字符。后续操作中注意路径处理。