liuxingxing

python常用命令

1、得到当前的路径:

os.path.split(os.path.realpath(__file__))[0]

2、当找不到包的时候

service_dir=join(dirname(dirname(abspath(__file__))),\'service\')

sys.path.append(service_dir)

3、图形化界面可以采用prettytable

4、打开文件时候,会多出来一些空格

      原因:read()到达文件末尾时,返回一个空字符串,而将这个空字符串显示出来就是一个空行;

      解决方法:

       with open(\'pi.digits.text\') as file_object:

           contents = file_object.read()

           print(contents.rstrip())

5、逐行读取

       with open(\'pi.digits.text\') as file_object:

           for line in file_object:

               print(line.rstrip())

6、读取所有的行

       with open(\'pi.digits.text\') as file_object:

           lines = file_object.readlines()

           for line in lines:

               print(line.rstrip())

7、写入

    with open(filename, \'w\') as file_object:

       file_object.write("123")

8、写入多行

    with open(filename, \'w\') as file_object:

       file_object.write("12\n")

      file_object.write("123\n")

9、存储和加载

      json.dump() 和 json.load() 来编码和解码JSON数据,用于处理文件

     json 模块提供了一种很简单的方式来编码和解码JSON数据。 其中两个主要的函数是 json.dumps() 和 json.loads()。

     json.dumps将一个Python数据结构转换为JSON

     json.loads将一个JSON编码的字符串转换回一个Python数据结构

    存储:

    with open(filename, \'w\') as file_object:

       json.dump("123", file_object)

    加载:

     with open(filename, \'w\') as file_object:

        son.load("123", file_object)

10、python导入第三方库

    https://jingyan.baidu.com/article/48b37f8dc107441a6564887e.html

11、写文件,有时候为了保持格式

     with open(filename, \'wb+\') as file_object:

 12、python的列表解析

     [values **2 for value in range(1,11)]

     [values **2 for value in range(1,11) if value == 2]

13、查看库里的所有函数

      dir(func)

14、python时间转换

       最近开发过程中经常需要将utc(协调时间)时间转换成CST(标准时间),总结如下:

  获取上海时间:

    import datetime

    from pytz import timezone

    datetime.datetime.now(timezone(\'Asia/Shanghai\')).strftime(\'%Y-%m-%d %H:%M:%S\') 通过datetime.datetime得到字符串

    start_time_datetime = datetime.datetime.strptime(start_time, "%Y-%m-%dT%H:%M:%SZ") 通过字符串得到datetime.datetime

 

    现在的utc时间,并且去掉时区 time_now = datetime.datetime.now(tz=pytz.timezone(\'UTC\')).replace(tzinfo=None)
我想应该可以增加时区吧

 

  时区进行转换:

    utc = "2014-09-18T10:42:16.126Z"

    UTC_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
utc_time = datetime.datetime.strptime(utc, UTC_FORMAT)
local_time = utc_time.astimezone(timezone(\'Asia/Shanghai\'))
print(local_time.strftime("%Y-%m-%d %H:%M:%S"))

utc时间转换
    utc_time = datetime.datetime.strptime(utc_data, UTC_FORMAT) + datetime.timedelta(hours=8)





   

    

分类:

技术点:

相关文章: