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]) #
print(time.localtime().tm_year) #
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) #
%y 两位数的年份表示(-)
%Y 四位数的年份表示(-)
%m 月份(-)
%d 月内中的一天(-)
%H 24小时制小时数(-)
%I 12小时制小时数(-)
%M 分钟数(=)
%S 秒(-)
%a 本地简化星期名称
%A 本地完整星期名称
%b 本地简化的月份名称
%B 本地完整的月份名称
%c 本地相应的日期表示和时间表示
%j 年内的一天(-)
%p 本地A.M.或P.M.的等价符
%U 一年中的星期数(-)星期天为星期的开始
%w 星期(-),星期天为星期的开始
%W 一年中的星期数(-)星期一为星期的开始
%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、import calender
①判断闰年: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) #
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('','')) 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')) #
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)
os.getcwd()用法:返回当前的工作目录
三、序列化:将python的字典转化为字符串传递给其他语言或保存
1、json序列化:将json类型的对象与json类型的字符串相互转换
import json
序列化
将json类型的对象与json类型的字符串相互转换,{} 与 [] 嵌套形成的数据(python中建议数据的从{}开始)
dic = {'a': 1, 'b': [1, 2, 3, 4, 5]} json_str = json.dumps(dic)
print(json_str, type(json_str) # {"a": 1, "b": [1, 2, 3, 4, 5]} <class 'str'> with open('', 'w', encoding='utf-8') as w:
json.dump(dic, w) 反序列化
json_str = '''{"a": 1, "b": [1, 2, 3, 4, 5]}'''
new_dic = json.loads(json_str) # json类型的字符串不认''
print(new_dic, type(new_dic)) # {'a': 1, 'b': [1, 2, 3, 4, 5]} <class 'dict'> with open('', '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('', 'wb') as w:
pickle.dump(dic, w) print(pickle.loads(res))
with open('', 'rb') as r:
print(pickle.load(r))
day17 十七、时间模块的更多相关文章
- Python—day17时间模块、系统模块、递推遍历、序列化
一.time'''时间戳(timestamp):time.time()延迟线程的运行:time.sleep(secs)(指定时间戳下的)当前时区时间:time.localtime([secs])(指定 ...
- python第十七天---时间模块、random模块
作完一个作业,开始新的学习: 有由今天的时间有限所有学习了以下两个模块,明天继续! 时间模块.random模块 import time #!usr/bin/env python #-*-coding: ...
- python时间模块-time和datetime
时间模块 python 中时间表示方法有:时间戳,即从1975年1月1日00:00:00到现在的秒数:格式化后的时间字符串:时间struct_time 元组. struct_time元组中元素主要包括 ...
- 浅谈Python时间模块
浅谈Python时间模块 今天简单总结了一下Python处理时间和日期方面的模块,主要就是datetime.time.calendar三个模块的使用.希望这篇文章对于学习Python的朋友们有所帮助 ...
- python_way ,day2 字符串,列表,字典,时间模块
python_way ,day2 字符串,列表,字典,自学时间模块 1.input: 2.0 3.0 区别 2.0中 如果要要用户交互输入字符串: name=raw_input() 如果 name=i ...
- python的时间模块
python有两个重要的时间模块,分别是time和datetime 先看time模块 表示时间的几种方法: 1)时间元组:time.struct_time(tm_year=2016, tm_mon ...
- s14 第5天 时间模块 随机模块 String模块 shutil模块(文件操作) 文件压缩(zipfile和tarfile)shelve模块 XML模块 ConfigParser配置文件操作模块 hashlib散列模块 Subprocess模块(调用shell) logging模块 正则表达式模块 r字符串和转译
时间模块 time datatime time.clock(2.7) time.process_time(3.3) 测量处理器运算时间,不包括sleep时间 time.altzone 返回与UTC时间 ...
- 第三十二节,datetime时间模块
首先要引入import datetime时间模块 datetime.date.today()模块函数 功能:输出系统年月日输出格式 2016-01-26[无参] 使用方法:datetime.date. ...
- 【python标准库模块一】时间模块time学习
本文介绍python的标准库模块time的常见用法 时间模块time 导入时间模块 import time 得到时间戳,这是统计从1970年1月1日0点0分到现在经过了多少秒,一般用于加减法一起用,比 ...
随机推荐
- wifipineapple外接网卡上网
买了一台wifipineapple, pineapple有两种版本, 第一种是3G版本,可以外接3G上网卡, 还有一种是wifi版本, 包含一个物理的网络插槽, 我买的是第二种 wifipineapp ...
- wpf 控件添加背景图片
方法一,xaml中: <控件> <控件.Background> <ImageBrush ImageSource="/WpfApplication1;compon ...
- Mac NPM 配置
1.NPM 简介 NPM(node package manager),通常称为 node 包管理器,是目前世界上最大的开源库生态系统.使用 NPM 可以对 node 包进行安装.卸载.更新.查看.搜索 ...
- 飞思卡尔单片机P&E开发工具硬件及软件
原文链接: http://blog.sina.com.cn/s/blog_8ebff8d7010121tm.html 1.HC(S)08系列 开发机硬件:USB-ML-12 CYCLONE PRO U ...
- Linux将yum源设置为阿里云的镜像源
第一步:备份原有镜像源 mv /etc/yum.repo.d/Centos-Base.repo /etc/yum.repo.d/Centos-Base.repo.bak 第二步:下载阿里云的镜像源 w ...
- 框架源码系列二:手写Spring-IOC和Spring-DI(IOC分析、IOC设计实现、DI分析、DI实现)
一.IOC分析 1. IOC是什么? IOC:Inversion of Control控制反转,也称依赖倒置(反转) 问题:如何理解控制反转? 反转:依赖对象的获得被反转了.由自己创建,反转为从IOC ...
- 在生成一个窗体的时候,点击窗体的右上角关闭按钮激发窗体事件的方法:窗体Frame为事件源,WindowsListener接口调用Windowsclosing()。
事件模式的实现步骤: 开发事件对象(事件发送者)——接口——接口实现类——设置监听对象 一定要理解透彻Gril.java程序. 重点:学会处理对一个事件源有多个事件的监听器(在发送消息时监听器收到 ...
- ubuntu 下无损扩展分区
命令扩展: http://www.cnblogs.com/greatfish/p/7347945.html http://www.cnblogs.com/wangxingggg/articles/68 ...
- 3D游戏图形引擎
转自:http://www.cnblogs.com/live41/archive/2013/05/11/3072282.html CryEngine 3 http://www.crydev.net/ ...
- 基金 、社保和QFII等机构的重仓股排名评测
基金前15大重仓股持仓股排名 基金重仓前15大个股,相较于同期沪深300的平均收益, 近1月:2.45%, 近3月:10.0%, 近1年:11.22%, 近3年:105.23%. 1,中国平安(SH6 ...