python常见命令

练习题答案

http://www.mamicode.com/info-detail-1113345.html

python常用标准库

http://lizhenliang.blog.51cto.com/7876557/1872538

python challenge

http://www.cnblogs.com/jimnox/archive/2009/12/08/tips-to-python-challenge.html

0. 搭建虚拟环境

sudo apt-get install python-pip

sudo apt-get install python-virtualenv #安装本地虚拟环境管理工具

mkdir ~/django # 创建目录

cd ~/django virtualenv venv #在~/django目录下,创建一个venv的虚拟环境

source venv/bin/activate #开启虚拟环境

1. 清屏

方法一     ----还是这个好!

import os

os.system("clear")

方法二

import subprocess

subprocess.call("clear")

2. 写文件内容的2个方法

法1

f = open(‘print.txt‘,‘w‘)

f.write("my name is hong")

f.close()

法2

f=open(‘print.txt‘,‘w‘)

print >> f,"my name is hong"

f.close()

3.  读文件内容的两种方法

法1

d=open(‘a.txt‘,‘r‘)

print d.readline #读取第一行内容

print d.readline #读取第2行内容

print d.read(100) #读取从0-100的所有内容,这里的100好像是字符数,可以随文本大小自行调整

d.seek(0) #使读取指针归0,也就是从0开始读取文本,和上条命令配合使用

法2

import linecache

print linecache.getline(‘a.txt‘,1) #读第一行

print linecache.getline(‘a.txt‘,2) #读第二行

4. 字符拼接的五种方法

1)

>>> print a+b

2)

>>> 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 apple

4)

>>> d="%()s %()s" %{‘‘:a,‘‘:b}

>>> print d

a = "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,3

a=[‘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 os

m=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.html

2) popen(...)

popen(command [, mode=‘r‘ [, bufsize]]) -> pipe

Open a pipe to/from a command returning a file object.

7. 查看引用次数

一切变量都是数据对象的引用, python中引用数目是从3开始,引用一次加1,去引用一次减1

python内部的引用计数,sys.getrefcount

import sys

a=‘hello‘

sys.getrefcount(‘hello‘)

输出为3---python中初始数为3

e=‘hello‘

sys.getrefcount(‘hello‘)

输出为4

a=1

sys.getrefcount(‘hello‘)

输出为3,说明引用被销毁一次。

总结一下对象会在一下情况下引用计数加1:

1.对象被创建:x=4

2.另外的别人被创建:y=x

3.被作为参数传递给函数:foo(x)

4.作为容器对象的一个元素:a=[1,x,‘33‘]

引用计数减少情况

1.一个本地引用离开了它的作用域。比如上面的foo(x)函数结束时,x指向的对象引用减1。

2.对象的别名被显式的销毁:del x ;或者del y

3.对象的一个别名被赋值给其他对象:x=789

4.对象从一个窗口对象中移除:myList.remove(x)

5.窗口对象本身被销毁:del myList,或者窗口对象本身离开了作用域。垃圾回收

8. 请将模块string的帮助文档保存为一个文件。

http://bbs.sjtu.edu.cn/bbstcon?board=Script&reid=1406189687

import string

import sys

out = sys.stdout

sys.stdout = open("help.txt", "w")

help(string)  #help(string)输出的信息会被记录到help.txt中

sys.stdout.close()

sys.stdout = out

9. 查看模块中函数的内置方法

例如,想知道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.html

1. 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,否则False

8. os.path.isdir()——判断指定对象是否为目录。是True,否则False。例:

>>> os.path.isfile("m1.py")

True

9. os.path.exists()——检验指定的对象是否存在。是True,否则False.例:

10. os.path.split()——返回路径的目录和文件名。例:

此处只是把前后两部分分开而已。就是找最后一个‘/‘。看例子:

11. os.getcwd()——获得当前工作的目录(get current work dir)

12. os.system()——执行shell命令,linux下的命令基本都能执行。例:

注意:此处运行shell命令时,如果要调用python之前的变量,可以用如下方式:

var=123

os.environ[‘var‘]=str(var) //注意此处[]内得是 “字符串”

os.system(‘echo $var‘)

13. os.chdir()——改变目录到指定目录

14. os.path.getsize()——获得文件的大小,如果为目录,返回0

15. os.path.abspath()——获得绝对路径。例:

16. os.path.join(path, name)——连接目录和文件名。例:

17.os.path.basename(path)——返回文件名

18. os.path.dirname(path)——返回文件路径

19. 获得程序所在的实际目录

import os

import sys

if __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]

执行结果


1

2

3

/home/jihite/ftp/del.py

(‘/home/jihite/ftp‘, ‘del.py‘)

/home/jihite/ftp 

细节——os.path.spilit()把目录和文件区分开


1

2

3

4

5

>>> 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/39080457

http://blog.csdn.net/zyz511919766/article/details/25136485/

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

import logging

logging.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函数对日志的输出格式及方式做相关配置

import logging

logging.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 message

Sun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info message

Sun, 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.WARNING

stream: 指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略

12. 常见模块

http://lizhenliang.blog.51cto.com/7876557/1872538

1、sys

1)sys.argv, 脚本名1.py, 命令行中执行python 1.py a b c, 脚本基本内容如下

import sys

print sys.argv[0]         #1.py

print sys.argv[1]         #a

print sys.argv            #[‘1.py‘, ‘a‘, ‘b‘, ‘c‘]

print len(sys.argv)       #算上脚本名长度为4

print len(sys.argv[1:])   #获取参数长度3。

2)标准输入

import sys

name = raw_input("Please input your name: ")

print name

拓展:a.py的标准输出作为b.py的标准输入

# cat a.py

import sys

sys.stdout.write("123456\n")

sys.stdout.flush()

# cat b.py

import sys

print sys.stdin.readlines()

命令行中执行 python a.py | python b.py    输出结果为:[‘123456\n‘]

3)实时动态输出信息,每隔一秒输出数字

import sys

for i in range(5):

import time

print i,

sys.stdout.flush()

time.sleep(1)

2、os

1)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

文件查找,支持通配符(*、?、[])


1

2

3

4

5

6

7

8

9

10

11

# 查找目录中所有以.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、math

5、random

6、platform

7、pikle与cPikle

示例,将字典序列化到文件:

>>> import pickle

>>> 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)

>>> print data

{‘a‘: 1, ‘c‘: 3, ‘b‘: 2}

8、subprocess

1)subprocess.call():运行命令与参数。等待命令完成,返回执行状态码。


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

>>> import subprocess

>>> retcode = subprocess.call(["ls", "-l"])  #这里的“-l”是字母L,其实就是执行ls -l

total 504

-rw-r--r-- 1 root root      54 Nov  2 06:15 data.pkl

>>> retcode #正确执行就返回0

0

>>> retcode = subprocess.call(["ls", "a"])

ls: cannot access a: No such file or directory

>>> retcode #执行失败就返回非0

2

# 也可以这样写

>>> subprocess.call(‘ls -l‘, shell=True)

>>> subprocess.check_call("ls a", shell=True)

#subprocess.check_call():运行命令与参数。如果退出状态码非0,引发CalledProcessError异常,包含状态码。

ls: cannot access a: No such file or directory

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

File "/usr/lib/python2.7/subprocess.py", line 540, in check_call

raise CalledProcessError(retcode, cmd)

subprocess.CalledProcessError: Command ‘ls a‘ returned non-zero exit status 2

拓展:

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 |grep eth0‘, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

>>> p.communicate()

......  # 元组形式返回结果

>>> p.pid  #获取子进程PID

57039

>>> p.wait() #等待子进程终止,返回状态码

0

>>> p.returncode #返回子进程状态码

0

subprocess.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:队列,数据存放在内存中,一般用于交换数据。

>>> from Queue import Queue

>>> q = Queue()

>>> q.put(‘test‘) #写入项目到队列

>>> q.qsize()

1

>>> q.get()  #从队列中删除并返回一个项目

‘test‘

>>> q.qsize() #返回队列大小

0

>>> q.full()  #如果队列是满的返回True,否则返回False

False

>>> q.empty() #如果队列为空返回True,否则返回False

True

10、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

定义最终日志格式

import logging

format = 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("info message.")

error_logger.error("error message!")

输出结果:

# python test.py

2016-07-02 06:52:25,624 - WARNING test.py [line:49] info message.

2016-07-02 06:52:25,631 - ERROR test.py [line:50] error message!

# cat info.log

2016-07-02 06:52:25,624 - WARNING test.py [line:49] info message.

# cat error.log

2016-07-02 06:52:25,631 - ERROR test.py [line:50] error message!

12、ConfigParser

13、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正整数指定读取多少字节

>>> import urllib, urllib2

>>> response = urllib.urlopen("http://www.baidu.com";)   # 获取的网站页面源码

>>> response.readline()

‘<!DOCTYPE html>\n‘

>>> response.getcode()

200

>>> response.geturl()

http://www.baidu.com‘;

注意:使用read()来读取网页内容时,指针会随着读取内容位置而变化,如果内容读完了,在执行response.read()就会返回一个空字符串,目前不知道怎么使指针清0的方法,一个替代方法是:使用response.close(),这样就需要重新定义变量,一切重新开始。

14、json

15、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

>>> timearray

time.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 timestap

1412955630

例子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 styletime

2017-09-20 10:25:14

可参考

http://blog.csdn.net/u014595019/article/details/50761763 ,里面有2个错误

1. 时间戳转换为指定格式日期的方法2,比实际时间差8个小时,utc国际时间的原因吧

2. 获取当前时间并转换为指定日期格式,方法1的代码第5行参数,应该是now

16. 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.max

datetime.time(23, 59, 59, 999999)


time.min

所能表示的最小时间

>>> time.min

datetime.time(0, 0)


time.resolution

时间最小单位,1微妙

>>> time.resolution

datetime.timedelta(0, 0, 1)

datetime.timedelta()类:


1

2

3

4

5

6

7

8

9

10

# 获取昨天日期

>>> 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-29

import datetime

print datetime.date.today()

1.3 用datetime返回一个月前的日期:比如今天是2013-3-29 一个月前的话:2013-02-27

解答:

>>> now=date.today()

>>> print now

2017-09-18

>>> onemonthago=now-datetime.timedelta(days=30)

>>> print onemonthago

2017-08-19

拓展

>>> date=datetime.datetime(2013,03,29) - datetime.timedelta(days=30)

>>> print date

2013-02-27 00:00:00

>>> time_format=date.strftime(‘%Y%m%d‘)

>>> print time_format

20130227

十三. pycharm操作

http://bbs.pythontab.com/thread-4633-1-1.html

原文地址:https://www.cnblogs.com/regit/p/8514713.html

时间: 2024-08-30 17:03:10

python常见命令的相关文章

备起来!Linux安全运维常见命令小贴士

备起来!Linux安全运维常见命令小贴士 常用命令 1. 查找关键词并统计行数 cat 2015_7_25_test_access.log | grep "sqlmap" | wc -l 2. 删除含有匹配字符的行 sed -i '/Indy Library/d' 2015_7_25_test_access.log 3. 查找所有日志中的关键词 find ./ -name "*.log" |xargs grep "sqlmap" |wc -l 4

一个linux常见命令的列表

这是一个linux常见命令的列表. 那些有• 标记的条目,你可以直接拷贝到终端上而不需要任何修改,因此你最好开一个终端边读边剪切&拷贝. 所有的命令已在Fedora和Ubuntu下做了测试 命令 描述 • apropos whatis 显示和word相关的命令. 参见线程安全 • man -t man | ps2pdf - > man.pdf 生成一个PDF格式的帮助文件   which command 显示命令的完整路径名   time command 计算命令运行的时间 • time c

linux常见命令的列表

http://www.pixelbeat.org/cmdline_zh_CN.html 命令 描述 ? apropos whatis 显示和word相关的命令. 参见线程安全 ? man -t man | ps2pdf - > man.pdf 生成一个PDF格式的帮助文件   which command 显示命令的完整路径名   time command 计算命令运行的时间 ? time cat 开始计时. Ctrl-d停止.参见sw ? nice info 运行一个低优先级命令(这里是info

linux常见命令列表

转自 http://www.pixelbeat.org/cmdline_zh_CN.html 这是一个linux常见命令的列表.那些有? 标记的条目,你可以直接拷贝到终端上而不需要任何修改,因此你最好开一个终端边读边剪切&拷贝. 所有的命令已在Fedora和Ubuntu下做了测试 命令 描述 ? apropos whatis 显示和word相关的命令. 参见线程安全 ? man -t man | ps2pdf - > man.pdf 生成一个PDF格式的帮助文件   which comman

ansys 常见命令集合

APDL换行与续行- APDL规定每行72个字符 如果要写表达式A=C1+C2 (C1与C2都为表达式 可以用 B=C1 A=B+C2 将一行拆成两行来做但是如果不是表达式,而是输入一个命令参数过多的话,可以用续行命令RMORE,格式如下: RMORE, R7, R8, R9, R10, R11, R12 这个命令每次也只能输入6个参数,如果多于6个,可以重复使用RMORE就可以输入13-18,19-24等等.另外,于上面续行相应的是换行,一行命令太短可以使用多个命令共一行 $",没有双引号.这

Linux常见命令详解

1.Linux语法格式 命令 -参数 命令:是告诉干什么 命令后面有空格 -是固定 参数是告诉怎么干. 如果不需要参数,也不要-. 如果选项是个完整的单词,必须是--. 例如:杀鸡 杀是命令 怎么杀是参数. 如果有多个参数,可以分开写,也可以连起来写,同类项组合. 保留-,合并字母. 2.帮助命令 ls --help man(manual) ls(更多的是以手册形式来展现) whatis ls 当我们使用命令记不住的时候,只有记住开头,我们可以通过TAB键补全. 当我们只记住命令中间了部分的时候

Linux常见命令 ls cd type whatis date man cal hwclock

Linux常见命令:[可选项],<必须项>,-可重复多次 ,| 多选一  ,{}分组 ls(list) -l:long 长格式,一个文件或目录显示一行  文件类型:   -:普通文件   d:目录文件   b:块设备文件(block)   c:字符设备文件(character)   l:符号链接文件(symbolic link file)   p:命令管道文件(pipe)   s:套接字文件(socket)     文件权限(9位,每三位一组,每组rwx):  文件硬链接次数  文件属主(ow

python常见异常分类与处理方法

Python常见异常类型大概分为以下类: 1.AssertionError:当assert断言条件为假的时候抛出的异常 2.AttributeError:当访问的对象属性不存在的时候抛出的异常 3.IndexError:超出对象索引的范围时抛出的异常 4.KeyError:在字典中查找一个不存在的key抛出的异常 5.NameError:访问一个不存在的变量时抛出的异常 6.OSError:操作系统产生的异常 7.SyntaxError:语法错误时会抛出此异常 8.TypeError:类型错误,

Memcached 常见命令 telnet 使用方法介绍

Memcached 常见命令: telnet 使用方法介绍: (1)建立telnet连接,命令"telnet 127.0.0.1 11211".win7下会提示"telnet不是内部或外部命令",解决方法是"控制面板"-->"程序和功能"-->"打开或关闭windows功能"-->勾选"telnet客户端". (2)添加数据--命令"add name 0 60