python全栈开发 day17 十七、时间模块

一、时间模块

import time
print(time)     # <module 'time' (built-in)>


import time
print('暂停开始')
secs = 3
time.sleep(secs)   #  延迟线程的运行
print('暂停结束')

重点:

1、时间戳:可以作为数据的唯一标识,是相对于1970-1-1-0:0:0 时间插值

import time
print(time.time())      # 1554878644.9071436

2、当前时区时间:东八区(上海时区)

print(time.localtime())
# time.struct_time(tm_year=2019, tm_mon=4, tm_mday=10, tm_hour=14, tm_min=48,
# tm_sec=29, tm_wday=2, tm_yday=100, tm_isdst=0)

# 年
print(time.localtime()[0])        # 2019
print(time.localtime().tm_year)   # 2019

3、格林威治时区

import time
print(time.gmtime())


4、可以将时间戳转化为时区的time

import time
print(time.localtime(5656565653))
print(time.localtime(time.time()))


5、应用场景 => 通过时间戳,获得该时间戳能反映出的年月日等信息

import time
print(time.localtime(5656565653).tm_year)      # 2149
%y 两位数的年份表示(00-99%Y 四位数的年份表示(000-9999%m 月份(01-12%d 月内中的一天(0-31%H 24小时制小时数(0-23%I 12小时制小时数(01-12%M 分钟数(00=59%S 秒(00-59%a 本地简化星期名称
%A 本地完整星期名称
%b 本地简化的月份名称
%B 本地完整的月份名称
%c 本地相应的日期表示和时间表示
%j 年内的一天(001-366%p 本地A.M.或P.M.的等价符
%U 一年中的星期数(00-53)星期天为星期的开始
%w 星期(0-6),星期天为星期的开始
%W 一年中的星期数(00-53)星期一为星期的开始
%x 本地相应的日期表示
%X 本地相应的时间表示
%Z 当前时区的名称
%% %号本身

6、格式化时间

格式化的字符串,时间tuple

import time
res = time.strftime('%Y-%m-%d %j days')
print(res)      # 2019-04-10 200 days

t = (2020, 4, 10, 10, 19, 22, 2, 200, 0)
res = time.strftime('%Y-%m-%d %j days', t)
# 没有确保数据的安全性,只是将元组信息转化为时间格式的字符串
print(res)          # 2020-04-10 200 days


7、需求:输入一个年份,判断其是否是闰年

解析:
#    1.能被400整除 year % 400 == 0
#    2.能被4整除不能被100整除  year % 4 == 0 and year % 100 != 0

# 方式一:
# year = int(input('year:>>>'))
# b1 = year % 400 == 0
# b2 = year % 4 == 0 and year % 100 != 0
# if b1 or b2:
#     print('是闰年')
# else:
#     print('不是闰年')

# 方式二:
# import calendar
# print(calendar.isleap(2018))     # False   # 判断是否为闰年


8、

# ①判断闰年:calendar.isleap(year)
import calendar
print(calendar.isleap(2000))     # True

# ②查看某年某月日历:calendar.month(year, month)
import calendar
print(calendar.month(2019,4))

# ③查看某年某月起始星期与当月天数:calendar.monthrange(year, month)
import calendar
print(calendar.monthrange(2019, 4))     # (0,30)
print(calendar.monthrange(2019, 3))     # (4,31)

# ④查看某年某月某日是星期几:calendar.weekday(year, month, day)
import calendar
print(calendar.weekday(2019, 4, 10))     # 2   # 星期是从0开始,0代表星期一

9、datatime 可以运算的时间

import datetime
print(datetime)     # <module 'datetime' from 'D:\\Python36\\lib\\datetime.py'>

res = datetime.datetime.now()
print(res)        # 2019-04-10 15:30:39.649993
print(type(res))  # <class 'datetime.datetime'>

day = datetime.timedelta(days=1)
print(day)        # 1 day, 0:00:00
print(type(day))  # <class 'datetime.timedelta'>

# res与day都是对象,可以直接做运算
print(res-day)    # 2019-04-09 15:50:15.130227
# ①当前时间:datetime.datetime.now()
import datetime
res = datetime.datetime.now()
print(res)        # 2019-04-10 15:30:39.649993

# ②昨天:datetime.datetime.now() + datetime.timedelta(days=-1)
import datetime
res = datetime.datetime.now() + datetime.timedelta(days=-1)
print(res)      # 2019-04-09 15:44:19.486885

# ③修改时间:datatime_obj.replace([...])
import datetime
res = datetime.datetime.now()
print(res.replace(year=2200))     # 2200-04-10 15:30:39.649993

# ④格式化时间戳:datetime.date.fromtimestamp(timestamp)
print(datetime.date.fromtimestamp(5656565653))    # 2149-04-01

二、系统模块

1、sys:系统

import sys

print(sys)          # <module 'sys' (built-in)>

print(sys.argv)     # ['D:/SH-fullstack-s3/day17/part1/系统模块.py']

print(sys.path)     # *****

# 退出程序,正常退出时exit(0)
print(sys.exit(0))

# 获取Python解释程序的版本信息
print(sys.version)    # 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)]

print(sys.maxsize)    # 9223372036854775807
a = 922337203685477580712321
print(a, type(a))    # 922337203685477580712321 <class 'int'>

# 操作系统平台名称
print(sys.platform)  # win32

2、os:操作系统

import os

# 1、生成单级目录:os.mkdir('dirname')
# print(os.mkdir('aaa'))     # 不存在创建,存在抛异常

# 2、生成多层目录:os.makedirs('dirname1/.../dirnamen2')
# print(os.makedirs('a/b/c'))
# 3、移除多层空目录:os.removedirs('dirname1/.../dirnamen')
# print(os.removedirs('a/b/c'))
# 4、重命名:os.rename("oldname","newname")
# print(os.rename('111','222'))

# 5、删除文件:os.remove
# print(os.remove('ccc.py'))

# 6、工作目录(当前工作目录):os.getcwd()
# print(os.getcwd())    # D:\SH-fullstack-s3\day17\part1  # 当前工作目录

# 7、删除单层空目录(删除文件夹):os.rmdir('dirname')
# print(os.rmdir('bbb'))
# print(os.rmdir('bbb/eee'))
# print(os.remove('bbb/ddd.py'))
# 8、移除多层空目录:os.removedirs('dirname1/.../dirnamen')

# 9、列举目录下所有资源:os.listdir('dirname')
# print(os.listdir(r'D:\SH-fullstack-s3\day17'))    # ['part0', 'part1']

# 10、路径分隔符:os.sep
# print(os.sep)              # \

# 11、行终止符:os.linesep
# print(os.linesep)
# print(ascii(os.linesep))   # '\r\n'

# 12、文件分隔符:os.pathsep
# print(os.pathsep)            # ;

# 13、操作系统名:os.name
# print(os.name)       # nt

# 14、操作系统环境变量:os.environ
# print(os.environ)

# 15、执行shell脚本:os.system()
# print(os.system('dir'))

# 16、当前工作的文件的绝对路径
# print(__file__)   # D:/SH-fullstack-s3/day17/part1/系统模块.py

3、os.path:系统路径操作

import os.path

# 1、执行文件的当前路径:__file__
# print(__file__)      # D:/SH-fullstack-s3/day17/part1/系统模块.py

# 2、返回path规范化的绝对路径:os.path.abspath(path)
# print(os.path.abspath(r'a'))    # D:\SH-fullstack-s3\day17\part1\a

# 3、将path分割成目录和文件名二元组返回:os.path.split(path)
# print(os.path.split(r'D:\SH-fullstack-s3\day17\part1'))   # ('D:\\SH-fullstack-s3\\day17', 'part1')
# print(os.path.split(r'D:\SH-fullstack-s3\day17\part1\\')) # ('D:\\SH-fullstack-s3\\day17\\part1', '')

# 4、上一级目录:os.path.dirname(path)
# print(os.path.dirname(r'D:\SH-fullstack-s3\day17\part1'))  # D:\SH-fullstack-s3\day17

# 5、最后一级名称:os.path.basename(path)
# print(os.path.basename(r'D:\SH-fullstack-s3\day17'))      # day17

# 6、指定路径是否存在:os.path.exists(path)
# print(os.path.exists(r'D:\SH-fullstack-s3\day17\part1\系统模块.py'))  # True
# print(os.path.exists(r'ccc'))   # False

# 7、是否是绝对路径:os.path.isabs(path)
# print(os.path.isabs(r'D:\SH-fullstack-s3\day17\part1\aaa'))  # True
# print(os.path.isabs(r'aaa'))                                 # False

# 8、是否是文件:os.path.isfile(path)
# print(os.path.isfile(r'D:\SH-fullstack-s3\day17\part1\系统模块.py'))  # True
# print(os.path.isfile(r'D:\SH-fullstack-s3\day17\part1'))      # False

# 9、是否是路径:os.path.isdir(path)
# print(os.path.isdir(r'D:\SH-fullstack-s3\day17\part1'))   # True

# 10、路径拼接:os.path.join(path1[, path2[, ...]])
# print(os.path.join(r'D:\SH-fullstack-s3\day17\part1', 'a', 'b', 'c'))
# 结果为 D:\SH-fullstack-s3\day17\part1\a\b\c

# 11、最后存取时间:os.path.getatime(path)
# print(os.path.getatime(r'D:\SH-fullstack-s3\day17\part1\时间模块.py'))
# 结果为 1554883111.9426434

# 12、最后修改时间:os.path.getmtime(path)
# print(os.path.getmtime(r'D:\SH-fullstack-s3\day17\part1\时间模块.py'))
# 结果为 1554883111.948644

# 13、目标大小:os.path.getsize(path)
# print(os.path.getsize(r'D:\SH-fullstack-s3'))     # 4096
import sys
import os.path as os_path

# 1、重点:先将项目的根目录设置为常量 -> 项目中的所有目录与文件都应该参照次目录进行导包
# BASE_PATH = os.path.dirname(os.path.dirname(__file__))
# print(BASE_PATH)              # D:/SH-fullstack-s3/day17
# sys.path.append(BASE_PATH)    # 重点:将项目目录添加至环境变量


# 2、拼接项目中某一文件或文件夹的绝对路径
# file_path = os_path.join(BASE_PATH,'part1','时间模块.py')
# print(file_path)                    # D:/SH-fullstack-s3/day17\part1\时间模块.py
# print(os_path.exists(file_path))    # True


# 3、重点:normcase函数
# 通过normcase来添加项目根目录到环境变量
# print(os.path.normcase('c:/windows\\system32\\'))
# BASE_PATH = os_path.normcase(os_path.join(__file__,'a','aaa'))
# print(BASE_PATH)      # d:\sh-fullstack-s3\day17\part1\系统模块.py\a\aaa
# sys.path.append(BASE_PATH)

三、序列化

1、json:序列化

import json

# 将json类型的对象与json类型的字符串相互转换
# {} 与 [] 嵌套形成的数据(python中建议数据的从{}开始)

dic = {
    'a': 1,
    'b': [1, 2, 3, 4, 5]
}
# 序列化: 将python的字典转化为字符串传递给其他语言或保存

json_str = json.dumps(dic)
print(json_str)     # {"a": 1, "b": [1, 2, 3, 4, 5]}

with open('1', 'w', encoding='utf-8') as w:
    json.dump(dic, w)



# 反序列化
json_str = '''{"a": 1, "b": ['1', 2, 3, 4, 5]}'''
json_str = "{'a': 1, 'b': [1, 2, 3, 4, 5]}"
json_str = '''{"a": 1, "b": [1, 2, 3, 4, 5]}'''
new_dic = json.loads(json_str)  # json类型的字符串不认''
print(new_dic, type(new_dic))

with open('1', 'r', encoding='utf-8') as r:
    res = json.load(r)
    print(res)

2、pickle:序列化

可以将任意类型对象与字符串进行转换

import pickle
dic = {
    'a': 1,
    'b': [1, 2, 3, 4, 5]
}
res = pickle.dumps(dic)
print(res)

with open('2', 'wb') as w:
    pickle.dump(dic, w)

print(pickle.loads(res))
with open('2', 'rb') as r:
    print(pickle.load(r))

猜你喜欢

转载自www.cnblogs.com/zhangguosheng1121/p/10686277.html