Python脚本路径、时间处理、编码
import os, sys # 获取当前脚本所在路径 scriptRunPath = os.path.abspath(__file__) print(scriptRunPath) # 获取当前脚本的上级目录 dirScriptRunPath = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) print(dirScriptRunPath) # 路径拼接单层 path = os.path.join(dirScriptRunPath, 'script') print(path) # 创建单层路径 os.mkdir(path) # 路径拼接多层 path = os.path.join(dirScriptRunPath, 'script', 'a', 'b', 'c') print(path) # 创建多层路径 os.makedirs(path) # queue.Queue 先进先出队列 # queue.LifoQueue 后进先出队列 # queue.PriorityQueue 优先级队列 # queue.deque 双向队列 ques = queue.Queue() # 向队列中添加元素 ques.put('a') # 取出队列中元素 print(ques.get()) # maxsize 队列的最大元素个数,当队列内的元素达到这个值时,后来的元素默认会阻塞,等待队列腾出位置 # qsize() 获取当前队列中元素的个数,也就是队列的大小 # empty() 判断当前队列是否为空,返回True或者False # full() 判断当前队列是否已满,返回True或者False print('队列中元素个数: %s' % ques.qsize()) # https://blog.csdn.net/weixin_44777680/article/details/108975808 # 把路径分为目录和文件两个部分,以列表返回。 path = os.path.split(os.path.abspath(__file__)) # 添加新路径到环境变量 newPath = sys.path.append(path) newPath = sys.path.insert(0, path) print(newPath) # 获取当前工作目录 cur_path = os.getcwd() # 切换工作目录 os.chdir(dirpath) # Windows路径分隔符 os.path.sep # Linux路径分隔符 os.path.altsep
pthon提示-bash: ./monitor.py: /usr/bin/python^M: bad interpreter: No such file or directory错误解决方法 1.查看文件是dos格式还是unix格式: vi monitor.py :set ff 2.如果是dos格式,则将文件转换为unix格式 :set ff=unix :wq
import os, sys, time, datetime def line_file_test(): print(time.strftime("%Y-%m-%d %H:%M:%S")) # 获取当前时间 print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) # 获取当前时间 print(datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')) # 获取当前UTC时间 print(sys._getframe().f_lineno) # 获取当前行号(行数) print(os.path.abspath(__file__)) # 获取当前Python文件的完整路径 print(os.path.basename(__file__)) # 获取当前Python文件文件名 print(os.path.splitext(os.path.basename(__file__))[0]) # 获取文件名并去掉文件名后缀 print(sys._getframe().f_code.co_name) # 在函数内部获取当前函数名 if __name__ == '__main__': line_file_test()
#!/usr/bin/python3 # -*- coding: utf-8 -*- # UTC时间与北京时间相互转换 import datetime, time def compare_timestamps(): """比较不同类型的时间戳""" print("=== 时间戳对比 ===") # 1. Unix时间戳 unix_ts = time.time() print(f"1. Unix时间戳: {unix_ts}") print(f" 对应时间: {datetime.datetime.fromtimestamp(unix_ts)}") # 2. Windows FILETIME windows_epoch = datetime.datetime(1601, 1, 1) unix_epoch = datetime.datetime(1970, 1, 1) epoch_diff = (unix_epoch - windows_epoch).total_seconds() filetime_ts = (unix_ts + epoch_diff) * 10 ** 7 print(f"2. Windows FILETIME: {filetime_ts:,}") # 3. 毫秒时间戳 millis_ts = int(unix_ts * 1000) print(f"3. 毫秒时间戳: {millis_ts}") # 4. 微秒时间戳 micros_ts = int(unix_ts * 1_000_000) print(f"4. 微秒时间戳: {micros_ts}") # 5. 纳秒时间戳(Python 3.7+) if hasattr(time, 'time_ns'): nanos_ts = time.time_ns() print(f"5. 纳秒时间戳: {nanos_ts:,}") # 6. 可读格式 iso_format = datetime.datetime.now().isoformat() print(f"6. ISO格式: {iso_format}") def get_windows_timestamp(): """ 获取Windows FILETIME时间戳 (自1601年1月1日以来的100纳秒间隔数) """ # Unix时间戳(1970年1月1日至今的秒数) unix_time = time.time() # Windows FILETIME起始时间(1601-01-01)到Unix起始时间(1970-01-01)的秒数 windows_epoch = datetime.datetime(1601, 1, 1) unix_epoch = datetime.datetime(1970, 1, 1) epoch_difference = (unix_epoch - windows_epoch).total_seconds() # 转换为100纳秒间隔数 windows_time = (unix_time + epoch_difference) * 10_000_000 return int(windows_time) # Windows FILETIME时间戳为18位的数字,例:timestamp = 132979302739322498 win_timestamp = get_windows_timestamp() print(f"Windows FILETIME时间戳:{win_timestamp}") # 将Windows FILETIME时间戳转换为Linux UTC时间 value = datetime.datetime(1601, 1, 1, tzinfo=datetime.timezone.utc) + datetime.timedelta(seconds=win_timestamp / 10_000_000) print(f"将Windows UTC时间戳转换为Linux UTC时间:{value}") # 格式化UTC时间为标准的ISO 8601格式(UTC) UTC_FORMAT = value.strftime('%Y-%m-%dT%H:%M:%SZ') print(f"格式化UTC时间为标准的ISO 8601格式(UTC):{UTC_FORMAT}") # 将UTC时间字符串转换为时间数组 UTC_TIME = time.strptime(UTC_FORMAT, '%Y-%m-%dT%H:%M:%SZ') print(f"将UTC时间字符串转换为时间数组:{UTC_TIME}") # 将UTC时间数组转换为UTC时间戳(秒) utc_timestamp = time.mktime(UTC_TIME) print(f"将UTC时间数组转换为UTC时间戳(秒):{utc_timestamp}") # 将UTC时间戳转换为东八区时间戳(秒) BJ_timestamp = utc_timestamp + 8 * 60 * 60 print(f"将UTC时间戳转换为东八区时间戳:{BJ_timestamp}") # 将东八区时间戳转换为时间字符串格式 LOCALTIME = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(BJ_timestamp)) print(f"将东八区时间戳转换为时间字符串格式:{LOCALTIME}") # 获取当前时间 local_time = time.strftime("%Y-%m-%d %H:%M:%S") print(f"当前时间字符串:{local_time} {type(local_time)}") # 将当前时间字符串转换为标准的ISO 8601格式(UTC) iso_utc = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.localtime(time.mktime(time.strptime(local_time, '%Y-%m-%d %H:%M:%S')) - 8 * 60 * 60)) print(f"将当前时间字符串转换为标准的ISO 8601格式(UTC):{iso_utc}")
#!/usr/bin/python3 # -*- coding: utf-8 -*- # 将北京时间字符串转换为ISO 8601格式(UTC)的Unix时间戳(秒),示例: "2024-02-29 10:20:24" -> 1709259624 # zoneinfo python3.9以上版本使用,3.9以下版本使用pytz import pytz from zoneinfo import ZoneInfo from datetime import datetime, timedelta, timezone # s字符串时区为东八区(Asia/Shanghai) s = "2025-10-31 15:44:00" sh_tz = pytz.timezone("Asia/Shanghai") local_dt = sh_tz.localize(datetime.strptime(s, "%Y-%m-%d %H:%M:%S")) # 转为时间戳 timestamp = int(local_dt.timestamp()) # 转为 UTC,输出ISO 8601(UTC,用Z结尾) iso_utc = local_dt.astimezone(pytz.UTC).strftime("%Y-%m-%dT%H:%M:%SZ") print(timestamp) print(iso_utc) # sh_tz = ZoneInfo("Asia/Shanghai") sh_tz = timezone(timedelta(hours=8)) # 始终按UTC+8,可以不用zoneinfo dt = datetime.strptime(s, "%Y-%m-%d %H:%M:%S") iso_utc = dt.replace(tzinfo=sh_tz).astimezone(timezone.utc).isoformat(timespec='seconds').replace("+00:00", "Z") timestamp_utc = int(dt.timestamp()) print("UTC timestamp (秒):", timestamp_utc) print("ISO 8601 (UTC):", iso_utc)
#!/usr/bin/env python # -*- coding:utf-8 -*- # __author__ = from datetime import datetime, timedelta # 获取今天的日期 today = datetime.now() # 获取前一天3小时前的日期 yesterday = today - timedelta(days=1, hours=3) # 输出结果 print("Yesterday's date:", yesterday.strftime('%Y-%m-%d %H:%M:%S'))
#!/usr/bin/env python # -*- coding:utf-8 -*- # __author__ = # pip install arrow import arrow # 获取当前时间 now = arrow.now() print(now) # 距现在一年后一月前 future = now.shift(years=1, months=-1).format('YYYY-MM-DD HH:mm:ss') print(future) # Monday = 0, Tuesday = 1 .. Sunday = 6 future = now.shift(weekday=0).format('YYYY-MM-DD HH:mm:ss') print(future) # 一天前 future = now.shift(days=-1).format('YYYY-MM-DD HH:mm:ss') print(future) # 3小时前 past = now.shift(hours=-3).format('YYYY-MM-DD HH:mm:ss') print(past) # 转换为纽约时区 ny_time = now.to('America/New_York').format('YYYY-MM-DD HH:mm:ss') print(ny_time) # 解析字符串为时间 parsed = arrow.get('2021-01-01 12:00:00').format('YYYY-MM-DD HH:mm:ss') print(parsed)
# "\u4f60\u597d"unicode类型的字符解码 python3的解决办法:"\u4f60\u597d".encode('utf-8').decode('utf-8') python2的解决办法:"\u4f60\u597d".decode('unicode_escape') # 中文转换为unicode chinese_string = "你好,世界" chinese_unicode = chinese_string.encode('unicode-escape').decode() print(chinese_unicode) chinese = chinese_unicode.encode().decode('unicode_escape') print(chinese) # unicode还原为中文 chinese_unicode = u'\u4f60\u597d\uff0c\u4e16\u754c' chinese = chinese_unicode.encode('utf-8').decode('utf-8') print(chinese) # bytes类型还原为中文(一般使用utf-8解码,也有可能是GBK) decoded_string = b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c' # print(str(decoded_string, encoding="utf-8")) chinese = decoded_string.decode('utf-8') print(chinese) # 中文转换为bytes类型 chinese_string = "你好,世界" bytes_data = chinese_string.encode('utf-8') # 使用UTF-8编码 print(bytes_data)
# 使用in操作符检查每个字符串是否在变量line中 if 'a' in line or 'b' in line: print(line) # 使用any()函数和一个生成器表达式来提高代码的可读性 if any(keyword in line for keyword in ['a', 'b']): # 使用集合来提高检查的效率,如果有大量的关键词需要检查 keywords = {'a', 'b'} if any(keyword in line for keyword in keywords):
# https://gitcode.com/gh_mirrors/go/gorilla-cli
[root@Rocky9 ~]# dnf install python3-pip.noarch [root@Rocky9 ~]# pip install gorilla-cli [root@Rocky9 ~]# gorilla "mysql语句格式化时间" Welcome to Gorilla. Use arrows to select date '+%s/%d/%y' -d '140402' -O -t '555555555' > 2000-01-01 12:00:00 mysql -e "SELECT date_format(NOW(),'%Y-%m-%d %H:%i') AS '结果'" mysql -u username -p database -e "SELECT DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:%s');" : #Do nothing
参考链接:
https://www.cnblogs.com/jfl-xx/p/8024596.html # python中时间、日期、时间戳的转换
https://www.cnblogs.com/hahaxzy9500/p/7685955.html # python解决'\u'开头的字符串转中文的方法
https://www.cnblogs.com/denise1108/p/10095042.html # python md5加密
https://github.com/PaulleDemon/PyUIBuilder # Python Tkinter GUI构建器
https://cloud.tencent.com/developer/article/2416110 # diskcache缓存库
https://www.cnblogs.com/traditional/p/11300448.html # dateutil库将时间字符串转为时间类型
浙公网安备 33010602011771号