python常见命令,python代码命令大全,http://www


http://www.bubuko.com/infodetail-1193119.html练习题答案http://www.byrx.net/info-detail-1113345.htmlpython常用标准库http://lizhenliang.blog.51cto.com/7876557/1872538python challengehttp://www.cnblogs.com/jimnox/archive/2009/12/08/tips-to-python-challenge.html0. 搭建虚拟环境sudo apt-get install python-pipsudo apt-get install python-virtualenv #安装本地虚拟环境管理工具mkdir ~/django # 创建目录cd ~/django virtualenv venv #在~/django目录下,创建一个venv的虚拟环境source venv/bin/activate #开启虚拟环境1. 清屏方法一 ----还是这个好!import osos.system("clear")方法二import subprocesssubprocess.call("clear")2. 写文件内容的2个方法法1f = open(‘print.txt‘,‘w‘)f.write("my name is hong")f.close()法2f=open(‘print.txt‘,‘w‘)print >> f,"my name is hong"f.close()3. 读文件内容的两种方法法1d=open(‘a.txt‘,‘r‘)print d.readline #读取第一行内容print d.readline #读取第2行内容print d.read(100) #读取从0-100的所有内容,这里的100好像是字符数,可以随文本大小自行调整d.seek(0) #使读取指针归0,也就是从0开始读取文本,和上条命令配合使用法2import linecacheprint linecache.getline(‘a.txt‘,1) #读第一行print linecache.getline(‘a.txt‘,2) #读第二行4. 字符拼接的五种方法1)>>> print a+b2)>>> print "%s %s" %(a,b)3)>>> c="{}{}".format(a,b)print c如果想调整一下输出参数的顺序,那么可以这样写b = "this is {1} {0}" .format ("my","apple"),那么输出结果就是this is apple my需要注意的是参数从0开始算参数位置太麻烦,有时候还出错,来种更人性化的方法b = "this is {whose} {fruit}" .format (fruit="apple",whose="my")print b输出为this is my apple4)>>> d="%()s %()s" %{‘‘:a,‘‘:b}>>> print da = "this is %(whose)s %(fruit)s" % {‘whose‘:‘my‘,‘fruit‘:‘apple‘}其中whose:my, whose是key位,my是word位5)请将a与b拼接成字符串c,并用逗号分隔。>>> c=",".join([a,b]) #join()函数中的参数a,b必须是字符串,>>> print c拓展请将a字符串的数字取出,并输出成一个新的字符串>>> a="aAsmr3idd4bgs7Dlsf9eAF">>> "".join([x for x in a if x.isdigit()])‘3479‘5. list转换成string的方法方法1,使用join函数--适用于列表元素必须是字符串,不能是int,比如1,2,3a=[‘a‘,‘b‘,‘c‘]info=‘‘.join(a)方法2,使用str函数--适用于列表元素是数字已知a =[1,2,3,6,8,9,10,14,17], 请将该list转换为字符串,例如 ‘123689101417‘.str(a)[1:-1].replace(‘, ‘,‘‘) #把逗号和空格替换为空‘123689101417‘相对应的, python中应该如何修改string呢?方法1. 转成list来修改info = "abc"a=list(info)a[2]=‘d‘info="".join(a)方法2. 使用repalce()函数s="i, am, lilei">>> s=s.replace("am","was")>>> s‘i,was,lilei‘6.在python命令行里,输入import this 以后出现的文档,统计该文档中,"be" "is" "than" 的出现次数。import osm=os.popen(‘python -m this‘).read() #python -m this 在linux命令行中执行,相当于在python命令行中执行import this。os.popen(...)可以直接执行命令行m=m.replace(‘\n‘,‘ ‘) #去掉回车符,可能造成语义混淆i=m.split(‘ ‘) #用空格作为分隔符,来找出每一个单词print [(x,i.count(x)) for x in [‘be‘,‘is‘,‘than‘]]注意:1)解释python -m http://www.cnblogs.com/xueweihan/p/5118222.html2) popen(...)popen(command [, mode=‘r‘ [, bufsize]]) -> pipe Open a pipe to/from a command returning a file object.7. 查看引用次数一切变量都是数据对象的引用, python中引用数目是从3开始,引用一次加1,去引用一次减1python内部的引用计数,sys.getrefcountimport sysa=‘hello‘sys.getrefcount(‘hello‘)输出为3---python中初始数为3e=‘hello‘sys.getrefcount(‘hello‘)输出为4a=1sys.getrefcount(‘hello‘)输出为3,说明引用被销毁一次。总结一下对象会在一下情况下引用计数加1:1.对象被创建:x=42.另外的别人被创建:y=x3.被作为参数传递给函数:foo(x)4.作为容器对象的一个元素:a=[1,x,‘33‘]引用计数减少情况1.一个本地引用离开了它的作用域。比如上面的foo(x)函数结束时,x指向的对象引用减1。2.对象的别名被显式的销毁:del x ;或者del y3.对象的一个别名被赋值给其他对象:x=7894.对象从一个窗口对象中移除:myList.remove(x)5.窗口对象本身被销毁:del myList,或者窗口对象本身离开了作用域。垃圾回收8. 请将模块string的帮助文档保存为一个文件。http://bbs.sjtu.edu.cn/bbstcon?board=Script&reid=1406189687import stringimport sysout = sys.stdoutsys.stdout = open("help.txt", "w")help(string) #help(string)输出的信息会被记录到help.txt中sys.stdout.close()sys.stdout = out9. 查看模块中函数的内置方法例如,想知道urlilb.urlopen里面都有什么方法可以调用1. 先用dir(urllib),找到里面有urlopen函数,这个时候用help, 或者dir来查看urllib.urlopen是看不到里面的方法的2. 给urllib.urlopen赋值给一个对象,比如 name = urllib.urlopen("http://www.baidu.com")3. 此时dir(name),就可以查看到urlopen的方法了。10. os模块详解http://www.cnblogs.com/kaituorensheng/archive/2013/03/18/2965766.html1. os.name——判断现在正在实用的平台,Windows 返回 ‘nt‘; Linux 返回’posix‘2. os.getcwd()——得到当前工作的目录。3. os.listdir()——指定所有目录下所有的文件和目录名。例:>>> os.listdir("/home")[‘axinfu‘]当前目录>>> os.listdir(".")[ ‘p1.py‘, ‘m1.py‘, ‘a.py‘, ‘.bash_logout‘, ‘m1.py‘, ‘.bashrc‘, ‘.viminfo‘, ‘loopdir‘, ‘.profile‘, ‘initrd.gz‘, ‘.bash_history‘]以列表的形式全部列举出来,其中没有区分目录和文件。4. os.remove()——删除指定文件 >>> os.remove("a.py")5. os.rmdir()——删除指定目录6. os.mkdir()——创建目录 注意:这样只能建立一层,要想递归建立可用:os.makedirs()7. os.path.isfile()——判断指定对象是否为文件。是返回True,否则False8. os.path.isdir()——判断指定对象是否为目录。是True,否则False。例: >>> os.path.isfile("m1.py")True9. os.path.exists()——检验指定的对象是否存在。是True,否则False.例:10. os.path.split()——返回路径的目录和文件名。例: 技术分享图片此处只是把前后两部分分开而已。就是找最后一个‘/‘。看例子: 技术分享图片11. os.getcwd()——获得当前工作的目录(get current work dir)12. os.system()——执行shell命令,linux下的命令基本都能执行。例: 技术分享图片注意:此处运行shell命令时,如果要调用python之前的变量,可以用如下方式:var=123os.environ[‘var‘]=str(var) //注意此处[]内得是 “字符串”os.system(‘echo $var‘)13. os.chdir()——改变目录到指定目录14. os.path.getsize()——获得文件的大小,如果为目录,返回015. os.path.abspath()——获得绝对路径。例: 技术分享图片16. os.path.join(path, name)——连接目录和文件名。例: 技术分享图片17.os.path.basename(path)——返回文件名 技术分享图片18. os.path.dirname(path)——返回文件路径 技术分享图片19. 获得程序所在的实际目录技术分享图片import osimport sysif __name__ == "__main__":print os.path.realpath(sys.argv[0])print os.path.split(os.path.realpath(sys.argv[0]))print os.path.split(os.path.realpath(sys.argv[0]))[0]技术分享图片执行结果
123/home/jihite/ftp/del.py(‘/home/jihite/ftp‘,‘del.py‘)/home/jihite/ftp 
细节——os.path.spilit()把目录和文件区分开
12345>>> import os>>> os.path.split("a/b/c/d")(‘a/b/c‘,‘d‘)>>> os.path.split("a/b/c/d/")(‘a/b/c/d‘,‘‘)
  11. logging模块http://blog.csdn.net/liuchunming033/article/details/39080457http://blog.csdn.net/zyz511919766/article/details/25136485/

1.简单的将日志打印到屏幕

importlogginglogging.debug(‘This is debug message‘)logging.info(‘This is info message‘)logging.warning(‘This is warning message‘)屏幕上打印:WARNING:root:This is warning message
默认情况下,logging将日志打印到屏幕,日志级别为WARNING;日志级别大小关系为:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET,当然也可以自己定义日志级别。

2.通过logging.basicConfig函数对日志的输出格式及方式做相关配置

importlogginglogging.basicConfig(level=logging.DEBUG,format=‘%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s‘,datefmt=‘%a, %d %b %Y %H:%M:%S‘,filename=‘myapp.log‘,filemode=‘w‘)logging.debug(‘This is debug message‘)logging.info(‘This is info message‘)logging.warning(‘This is warning message‘)./myapp.log文件中内容为:Sun, 24 May 2009 21:48:54 demo2.py[line:11] DEBUG This is debug messageSun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info messageSun, 24 May 2009 21:48:54 demo2.py[line:13] WARNING This is warning message
logging.basicConfig函数各参数:filename: 指定日志文件名filemode: 和file函数意义相同,指定日志文件的打开模式,‘w‘或‘a‘format: 指定输出的格式和内容,format可以输出很多有用信息,如上例所示:%(levelno)s: 打印日志级别的数值%(levelname)s: 打印日志级别名称%(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0]%(filename)s: 打印当前执行程序名%(funcName)s: 打印日志的当前函数%(lineno)d: 打印日志的当前行号%(asctime)s: 打印日志的时间%(thread)d: 打印线程ID%(threadName)s: 打印线程名称%(process)d: 打印进程ID%(message)s: 打印日志信息datefmt: 指定时间格式,同time.strftime()level: 设置日志级别,默认为logging.WARNINGstream: 指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略12. 常见模块http://lizhenliang.blog.51cto.com/7876557/18725381、sys1)sys.argv, 脚本名1.py, 命令行中执行python 1.py a b c, 脚本基本内容如下importsysprintsys.argv[0] #1.pyprintsys.argv[1] #aprintsys.argv #[‘1.py‘, ‘a‘, ‘b‘, ‘c‘]printlen(sys.argv) #算上脚本名长度为4printlen(sys.argv[1:]) #获取参数长度3。2)标准输入importsysname=raw_input("Pleaseinputyourname:")printname拓展:a.py的标准输出作为b.py的标准输入#cata.pyimportsyssys.stdout.write("123456\n")sys.stdout.flush()#catb.pyimportsysprintsys.stdin.readlines()命令行中执行 pythona.py|pythonb.py 输出结果为:[‘123456\n‘]3)实时动态输出信息,每隔一秒输出数字importsysforiinrange(5):importtime printi,sys.stdout.flush() time.sleep(1)2、os1)os.makedirs:在当前路径递归创建文件夹,例如当前目录为/home/axinfu注意:os.makedirs("./abc/b"), 不能写成os.makedirs("home/axinfu/abc/b"),这样会在当前目录下再创建一个home目录。2)目录树生成器os.walk(path)>>> for path,dir,file in os.walk(‘/home/axinfu/test‘):...print path...print dir...print file.../home/axinfu/test[][‘3.py‘, ‘2.py‘, ‘1.py‘]3、glob文件查找,支持通配符(*、?、[])
1234567891011#查找目录中所有以.sh为后缀的文件>>>glob.glob(‘/home/user/*.sh‘)[‘/home/user/1.sh‘,‘/home/user/b.sh‘,‘/home/user/a.sh‘,‘/home/user/sum.sh‘]#查找目录中出现单个字符并以.sh为后缀的文件>>>glob.glob(‘/home/user/?.sh‘)[‘/home/user/1.sh‘,‘/home/user/b.sh‘,‘/home/user/a.sh‘]#查找目录中出现a.sh或b.sh的文件>>>glob.glob(‘/home/user/[a|b].sh‘)[‘/home/user/b.sh‘,‘/home/user/a.sh‘]
4、math5、random6、platform7、pikle与cPikle示例,将字典序列化到文件:>>>importpickle>>>dict={‘a‘:1,‘b‘:2,‘c‘:3}>>>output=open(‘data.pkl‘,‘wb‘)#二进制模式打开文件>>>pickle.dump(dict,output)#执行完导入操作,当前目录会生成data.pkl文件>>>output.close()#写入数据并关闭读取序列化文件:>>>f=open(‘data.pkl‘)>>>data=pickle.load(f)>>>printdata{‘a‘:1,‘c‘:3,‘b‘:2}8、subprocess1)subprocess.call():运行命令与参数。等待命令完成,返回执行状态码。
123456789101112131415161718192021>>>importsubprocess>>>retcode=subprocess.call(["ls","-l"]) #这里的“-l”是字母L,其实就是执行ls -ltotal504-rw-r--r--1rootroot54Nov206:15data.pkl>>>retcode #正确执行就返回00>>>retcode=subprocess.call(["ls","a"])ls:cannotaccessa:Nosuchfileordirectory>>>retcode #执行失败就返回非02#也可以这样写>>>subprocess.call(‘ls-l‘,shell=True)>>>subprocess.check_call("lsa",shell=True)#subprocess.check_call():运行命令与参数。如果退出状态码非0,引发CalledProcessError异常,包含状态码。ls:cannotaccessa:NosuchfileordirectoryTraceback(mostrecentcalllast):File"<stdin>",line1,in<module>File"/usr/lib/python2.7/subprocess.py",line540,incheck_callraiseCalledProcessError(retcode,cmd)subprocess.CalledProcessError:Command‘lsa‘returnednon-zeroexitstatus2
拓展:1. 用subprocess.check_call("ls -l a", shell=True),ls后面可以加任意参数,需要抛出异常的时候使用不错,如果没异常就会正常显示2. 使用第一种方法 retcode=subprocess.call(["ls","-l"])时,可以在列表中加入指定文件夹名,比如retcode=subprocess.call(["ls","-l","a"]),把命令,参数,文件名都当作列表中的元素2)subprocess.Popen():例子1>>>p=subprocess.Popen(‘dmesg|grepeth0‘,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)>>>p.communicate()......#元组形式返回结果>>>p.pid #获取子进程PID57039>>>p.wait() #等待子进程终止,返回状态码0>>>p.returncode #返回子进程状态码0subprocess.PIPE提供了一个缓冲区,将stdout、stderr放到这个缓冲区中,p.communicate()读取缓冲区数据。缓冲区的stdout、stderr是分开的,可以以p.stdout.read()方式获得标准输出、错误输出的内容。例子2:标准输出作为下个Popen任务的标准输入:>>> p1 = subprocess.Popen(‘ls‘, stdout=subprocess.PIPE, shell=True)>>> p2 = subprocess.Popen(‘grep data‘, stdin=p1.stdout, stdout=subprocess.PIPE, shell=True)>>> p1.stdout.close() # 调用后启动p2,为了获得SIGPIPE>>> output = p2.communicate()[0] #这里的[0]貌似是指文件名>>> output‘data.pkl\n‘p1的标准输出作为p2的标准输入。这个p2的stdin、stdout也可以是个可读、可写的文件。9、Queue:队列,数据存放在内存中,一般用于交换数据。>>>fromQueueimportQueue>>>q=Queue()>>>q.put(‘test‘) #写入项目到队列>>>q.qsize()1>>>q.get() #从队列中删除并返回一个项目‘test‘>>>q.qsize() #返回队列大小0>>>q.full() #如果队列是满的返回True,否则返回FalseFalse>>>q.empty() #如果队列为空返回True,否则返回FalseTrue10、StringIO:将字符串存储在内存中,像操作文件一样操作。上面网站中的代码第一步是错误的,参考这个网站http://www.cnblogs.com/sislcb/archive/2008/11/27/1341996.html例子1>>> import StringIO>>> f=StringIO.StringIO()>>> f.write(‘hello‘)>>> f.getvalue()‘hello‘例子2,用一个字符串初始化StringIO,可以像读文件一样读取:>>> f=StringIO.StringIO(‘hello\nworld!‘)>>> f.read()‘hello\nworld!‘>>> s=StringIO.StringIO(‘hello world!‘)>>> s.seek(5)>>> s.write(‘~‘)>>> s.getvalue()‘hello~world!‘11、logging 几个主要的类
logging.Logger应用程序记录日志的接口
logging.Filter过滤哪条日志不记录
logging.FileHandler日志写到磁盘文件
logging.Formatter定义最终日志格式
importloggingformat=logging.Formatter(‘%(asctime)s-%(levelname)s%(filename)s[line:%(lineno)d]%(message)s‘)# 普通日志输出info_logger=logging.getLogger(‘info‘)#创建日志记录器info_logger.setLevel(logging.INFO)#设置日志级别,小于INFO的日志忽略info_file=logging.FileHandler("info.log")#日志记录到磁盘文件info_file.setFormatter(format) #设置日志格式info_logger.addHandler(info_file) #通过handler对象可以把日志内容写到不同的地方,python提供了十几种实用handler,比较常用有: StreamHandler: 输出到控制台 FileHandler: 输出到文件 BaseRotatingHandler: 可以按时间写入到不同的日志中。比如将日志按天写入不同的日期结尾的文件文件。 SocketHandler: 用TCP网络连接写LOG DatagramHandler: 用UDP网络连接写LOG SMTPHandler: 把LOG写成EMAIL邮寄出去# 错误日志输出error_logger=logging.getLogger(‘error‘)error_logger.setLevel(logging.ERROR)error_file=logging.FileHandler("error.log")error_file.setFormatter(format)error_logger.addHandler(error_file)#输出控制台(stdout)console=logging.StreamHandler()console.setLevel(logging.DEBUG)console.setFormatter(format)info_logger.addHandler(console)error_logger.addHandler(console)if__name__=="__main__":#写日志info_logger.warning("infomessage.")error_logger.error("errormessage!")输出结果:#pythontest.py2016-07-0206:52:25,624-WARNINGtest.py[line:49]infomessage.2016-07-0206:52:25,631-ERRORtest.py[line:50]errormessage!#catinfo.log2016-07-0206:52:25,624-WARNINGtest.py[line:49]infomessage.#caterror.log2016-07-0206:52:25,631-ERRORtest.py[line:50]errormessage!12、ConfigParser13、urllib与urllib2 urllib.urlopen()有几个常用的方法:
方法描述
getcode()获取HTTP状态码
geturl()返回真实URL。有可能URL3xx跳转,那么这个将获得跳转后的URL
info()返回服务器返回的header信息。可以通过它的方法获取相关值
next()获取下一行,没有数据抛出异常
read(size=-1)默认读取所有内容。size正整数指定读取多少字节
readline(size=-1)默认读取下一行。size正整数指定读取多少字节
readlines(sizehint=0)默认读取所有内容,以列表形式返回。sizehint正整数指定读取多少字节
>>>importurllib,urllib2>>>response=urllib.urlopen("http://www.baidu.com";)#获取的网站页面源码>>>response.readline()‘<!DOCTYPEhtml>\n‘>>>response.getcode()200>>>response.geturl()‘http://www.baidu.com‘;注意:使用read()来读取网页内容时,指针会随着读取内容位置而变化,如果内容读完了,在执行response.read()就会返回一个空字符串,目前不知道怎么使指针清0的方法,一个替代方法是:使用response.close(),这样就需要重新定义变量,一切重新开始。14、json15、time 这个time库提供了各种操作时间值。
方法描述示例
time.asctime([tuple])将一个时间元组转换成一个可读的24个时间字符串>>> time.asctime(time.localtime())‘Sat Nov 12 01:19:00 2016‘
time.ctime(seconds)字符串类型返回当前时间>>> time.ctime()‘Sat Nov 12 01:19:32 2016‘
time.localtime([seconds])默认将当前时间转换成一个(struct_timetm_year,tm_mon,tm_mday,tm_hour,tm_min, tm_sec,tm_wday,tm_yday,tm_isdst)>>> time.localtime()time.struct_time(tm_year=2016, tm_mon=11, tm_mday=12, tm_hour=1, tm_min=19, tm_sec=56, tm_wday=5, tm_yday=317, tm_isdst=0)
time.mktime(tuple)将一个struct_time转换成时间戳>>> time.mktime(time.localtime())1478942416.0
time.sleep(seconds)延迟执行给定的秒数>>> time.sleep(1.5)
time.strftime(format[, tuple])将元组时间转换成指定格式。[tuple]不指定默认以当前时间>>> time.strftime(‘%Y-%m-%d %H:%M:%S‘)‘2016-11-12 01:20:54‘
time.time()返回当前时间时间戳>>> time.time()1478942466.45977
1) time.localtime>>> time.localtime()time.struct_time(tm_year=2017, tm_mon=9, tm_mday=20, tm_hour=9, tm_min=57, tm_sec=50, tm_wday=2, tm_yday=263, tm_isdst=0)可以用time.localtime()[x]来取元组里面的值,[0]就是2017年份,tm_wday是周几,ubuntu好像周一是用0表示的。2)time.mktime(tuple):将一个struct_time转换成时间戳例子1,把指定的一个日期转换成时间戳>>> a="2014-10-10 23:40:30">>> timearray=time.strptime(a,‘%Y-%m-%d %H:%M:%S‘) # 将其转换为时间数组,使用strptime()可以转换成struct_time>>> timearraytime.struct_time(tm_year=2014, tm_mon=10, tm_mday=10, tm_hour=23, tm_min=40, tm_sec=30, tm_wday=4, tm_yday=283, tm_isdst=-1)>>> timestap=int(time.mktime(timearray)) #转换成时间戳>>> print timestap1412955630例子2>>> time.mktime(time.localtime())1505874314.0时间戳的作用好像是给时间加密,那么怎么把时间戳还原呢?方法1>>> timestamp=1505874314.0>>> timearray=time.localtime(timestamp)>>> styletime=time.strftime("%Y-%m-%d %H:%M:%S",timearray)>>> print styletime2017-09-20 10:25:14可参考http://blog.csdn.net/u014595019/article/details/50761763,里面有2个错误1.时间戳转换为指定格式日期的方法2,比实际时间差8个小时,utc国际时间的原因吧2.获取当前时间并转换为指定日期格式,方法1的代码第5行参数,应该是now16. datetime datetime库提供了以下几个类
描述
datetime.date()日期,年月日组成
datetime.datetime()包括日期和时间
datetime.time()时间,时分秒及微秒组成
datetime.timedelta()时间间隔
datetime.tzinfo()
datetime.date()类:
方法描述描述
date.max对象所能表示的最大日期datetime.date(9999, 12, 31)
date.min对象所能表示的最小日期datetime.date(1, 1, 1)
date.strftime()根据datetime自定义时间格式>>> date.strftime(datetime.now(), ‘%Y-%m-%d %H:%M:%S‘)‘2016-11-12 07:24:15
date.today()返回当前系统日期>>> date.today()datetime.date(2016, 11, 12)
date.isoformat()返回ISO 8601格式时间(YYYY-MM-DD)>>> date.isoformat(date.today())‘2016-11-12‘
date.fromtimestamp()根据时间戳返回日期>>> date.fromtimestamp(time.time())datetime.date(2016, 11, 12)
date.weekday()根据日期返回星期几,周一是0,以此类推>>> date.weekday(date.today())5
date.isoweekday()根据日期返回星期几,周一是1,以此类推>>> date.isoweekday(date.today())6
date.isocalendar()根据日期返回日历(年,第几周,星期几)>>> date.isocalendar(date.today())(2016, 45, 6)
datetime.datetime()类:
方法描述示例
datetime.now()/datetime.today()获取当前系统时间>>> datetime.now()datetime.datetime(2016, 11, 12, 7, 39, 35, 106385)
date.isoformat()返回ISO 8601格式时间>>> datetime.isoformat(datetime.now())‘2016-11-12T07:42:14.250440‘
datetime.date()返回时间日期对象,年月日>>> datetime.date(datetime.now())datetime.date(2016, 11, 12)
datetime.time()返回时间对象,时分秒>>> datetime.time(datetime.now()) datetime.time(7, 46, 2, 594397)
datetime.utcnow()UTC时间,比中国时间快8个小时>>> datetime.utcnow()datetime.datetime(2016, 11, 12, 15, 47, 53, 514210)
datetime.time()类:
方法描述示例
time.max所能表示的最大时间>>> time.maxdatetime.time(23, 59, 59, 999999)
time.min所能表示的最小时间>>> time.mindatetime.time(0, 0)
time.resolution时间最小单位,1微妙>>> time.resolutiondatetime.timedelta(0, 0, 1)
datetime.timedelta()类:
12345678910#获取昨天日期>>>date.today()-timedelta(days=1)datetime.date(2016,11,11)>>>date.isoformat(date.today()-timedelta(days=1))‘2016-11-11‘#获取明天日期>>>date.today()+timedelta(days=1)datetime.date(2016,11,13)>>>date.isoformat(date.today()+timedelta(days=1))‘2016-11-13‘
几个练习题。1.2 用datetime获取当前的日期,例如:2013-03-29import datetimeprint datetime.date.today()1.3 用datetime返回一个月前的日期:比如今天是2013-3-29 一个月前的话:2013-02-27解答:>>> now=date.today()>>> print now2017-09-18>>> onemonthago=now-datetime.timedelta(days=30)>>> print onemonthago2017-08-19拓展>>> date=datetime.datetime(2013,03,29) - datetime.timedelta(days=30)>>> print date2013-02-27 00:00:00>>> time_format=date.strftime(‘%Y%m%d‘)>>> print time_format20130227十三. pycharm操作http://bbs.pythontab.com/thread-4633-1-1.html

python常见命令

评论关闭