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

# Windows UTC时间戳
timestamp = 132979302739322498
# 将Windows UTC时间戳转换为Linux UTC时间字符串
value = datetime.datetime(1601, 1, 1) + datetime.timedelta(seconds=timestamp / 10000000)
print(value)
# 格式化UTC时间为标准的UTC时间格式
UTC_FORMAT = value.strftime('%Y-%m-%dT%H:%M:%SZ')
print(UTC_FORMAT)
# 格式化时间字符串
UTCTIME = value.strftime('%Y-%m-%d %H:%M:%S')
print(UTCTIME)
# 将时间字符串转换为时间数组
UTC_TIME = time.strptime(UTCTIME, '%Y-%m-%d %H:%M:%S')
print(UTC_TIME)
# 将时间数组转换为时间戳
utc_time = time.mktime(UTC_TIME)
# 将UTC时间戳转换为东八区的时间戳
beijing_time = utc_time + 8 * 60 * 60
print(beijing_time)
# 将时间戳转换为localtime然后格式化
LOCALTIME = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(beijing_time))
print(LOCALTIME)

# 将北京时间转换为UTC时间
local_time = time.strftime("%Y-%m-%d %H:%M:%S")
print(local_time)
print(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)))
复制代码
复制代码
# !/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']):
# 使用set()来提高检查的效率,如果有大量的关键词需要检查
keywords = {'a', 'b'}
if any(keyword in line for keyword in keywords):
[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构建器

posted @   風£飛  阅读(272)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
历史上的今天:
2018-01-17 CentOS上安装seafile
点击右上角即可分享
微信分享提示