python基础小汇总

文章结构

  1. pyton 中 args,*args 和 **kwargs参数用法介绍
  2. python中update()函数的用法介绍
  3. python 中的日期和时间处理模块datetime介绍

pyton 中 args,*args 和 **kwargs参数用法介绍:

python默认缺省参数
如下所示:

def test1(a,b=8):
    print(a,b)
#按照下面的执行
test1("cheng")
>>cheng,8
test1("cheng",99)
>>cheng,99
#甚至是改变参数的类型也可以
test1("cheng","wang")
>>cheng,wang

也可以参数名传参数,还是上面的test_1函数

test_1("ni","hao")
>>ni,hao
test_1(b="hao",a="ni")
>>ni,hao
#注意参数一定要保持一致性,如果是下面这种写法就是错误的
test_1(c="ni",d="hao")

对于可变长度的参数

def test_2(a,*b,**c):
    print("a="+a)
    print("b=",b)
    print("c=",c)
test_2("5")
>>a=5
b= ()
c= {}

######也可以换一种写法######
def test_2(a,*b,**c):
    print("a=",a)
    print("b=",b)
    print("c=",c)
test_2(5)#这一次的5表示int类型
>>a=5
b= ()
c= {}

参数可以是不定长度的列表,用*args表示(args表示参数名,可以任意取名)

def test_2(a,*b,**c):
    print("a="+a)
    for i in b:
        print("参数:",i)
b=[1,2,"cheng","lala"]
test_2("cheng",*b)###千万注意这里的"*"号
>>a=cheng
参数: 1
参数: 2
参数: cheng
参数: lala


#########如果是写成下面这种形式就不正确了##########
def test_2(a,*b,**c):
    print("a="+a)
    for i in b:
        print("参数:",i)
b=[1,2,"cheng","lala"]#也可以是元组("cheng","wang",1,2)
test_2("cheng",b)###如果不加上"*"号
>>a=cheng
参数: [1, 2, 'cheng', 'lala']


##########正确的写法等同于这一个#############
test_2("cheng","zhao","qian","sun","li",1,2,3,4)
>>a=cheng
参数: zhao
参数: qian
参数: sun
参数: li
参数: 1
参数: 2
参数: 3
参数: 4

接下来理解一下另一个可变长度的参数**kwargs,**kwargs可以当作容纳多个key和value的dict.

def test_3(arg1,**kwargs):  
    for key in kwargs:
        print ("%s:%s" %(key,kwargs[key]))  


kwargs = {"arg3": 3,"arg2":4,"arg3":6,"cheng":1,"yi":2} # dictionary  

test_3(1, **kwargs)  
#还是这种比较方便,也不用考虑对应的问题
>>arg3:6
arg2:4
cheng:1
yi:2



#########如果是不采用变长,而是固定了长度,就要注意参数名一一对应,举个例子


def test_4(arg1, arg2, arg3):  
    print ("arg1:", arg1)  
    print ("arg2:", arg2)  
    print ("arg3:", arg3) 

kwargs = {"arg3": 3, "arg2": 2} 
# 这个字典里的参数个数和名称都要和上面test_4的参数名称一一对应。

test_4(1, **kwargs) 
>>arg1: 1
arg2: 2
arg3: 3

######错误示范##########
def test_4(arg1, haha, arg3):  
    print ("arg1:", arg1)  
    print ("haha:", haha)  
    print ("arg3:", arg3) 

kwargs = { "args2":6,"arg3": 2} # dictionary  

test_4(1, **kwargs)  
>>结果报错
>TypeError: test_4() got an unexpected keyword argument 'args2' 

python中update()函数的用法介绍:

Python 字典 update() 方法用于更新字典中的键/值对,可以修改存在的键对应的值,也可以添加新的键/值对到字典中。

D = {'one': 1, 'two': 2}
D.update({'three': 3, 'four': 4})  # 传一个字典
D
>>{'four': 4, 'one': 1, 'three': 3, 'two': 2}
D.update(five=5, six=6)  # 传关键字
D
>>{'five': 5, 'four': 4, 'one': 1, 'six': 6, 'three': 3, 'two': 2}
D.update([('seven', 7), ('eight', 8)])  # 传一个包含一个或多个元祖的列表
D
>>{'eight': 8,
 'five': 5,
 'four': 4,
 'one': 1,
 'seven': 7,
 'six': 6,
 'three': 3,
 'two': 2}
 D.update(zip(['eleven', 'twelve'], [11, 12]))  # 传一个zip()函数
 D
 >>{'eight': 8,
 'eleven': 11,
 'five': 5,
 'four': 4,
 'one': 1,
 'seven': 7,
 'six': 6,
 'three': 3,
 'twelve': 12,
 'two': 2}
D.update(one=111, two=222)  # 使用以上任意方法修改存在的键对应的值
D
>>{'eight': 8,
 'eleven': 11,
 'five': 5,
 'four': 4,
 'one': 111,
 'seven': 7,
 'six': 6,
 'three': 3,
 'twelve': 12,
 'two': 222}

python 中的日期和时间处理模块datetime介绍:

前言
在开发工作中,我们经常需要用到日期与时间,如:

  1. 作为日志信息的内容输出
  2. 计算某个功能的执行时间
  3. 使用日期命名一个日志文件的名称
  4. 记录或者展示某个文章的发布或者修改时间
  5. 其他

python中提供了许多用于日期和时间进行操作的内置模块:time模块,datetime模块以及calendar模块,time模块是通过调用C库来实现的,所以有的方法在某些平台上面可能没法调用,但是其提供的大部分接口与C标准库的time.h基本上一致,与time模块相比,datetime模块提供的接口更加值观,易用,功能也更加强大。】

时间的表示形式

  1. 时间戳
  2. 格式化的时间字符串

    python中还有其他的时间表示形式:

  3. time模块的time.struct-time

  4. datetime模块的datetime类

以下简单介绍一下time.struct_time
time.struct_time包含如下属性:

下标/索引 属性名称 描述
0 tm_year 年份,如 2017
1 tm_mon 月份,取值范围为[1, 12]
2 tm_mday 一个月中的第几天,取值范围为[1-31]
3 tm_hour 小时, 取值范围为[0-23]
4 tm_min 分钟,取值范围为[0, 59]
5 tm_sec 秒,取值范围为[0, 61]
6 tm_wday 一个星期中的第几天,取值范围为[0-6],0表示星期一
7 tm_yday 一年中的第几天,取值范围为[1, 366]
8 tm_isdst 是否为夏令时,可取值为:0 , 1 或 -1

属性值的获取方式有两种:

  • 将其当成一种特殊的有序不可变序列通过下标索引获取各个元素的数值,比如t[0].
  • 也可以通过属性名的方式获取各个元素的数值,如t.tm_year。

需要说明的是struct_time实例的各个属性都是只读的,不可修改。

time模块

方法/属性 描述
time.altzone 返回与utc时间的时间差,以秒为单位(西区该值为正,东区该值为负)。其表示的是本地DST 时区的偏移量,只有daylight非0时才使用。
time.clock() 返回当前进程所消耗的处理器运行时间秒数(不包括sleep时间),值为小数;该方法Python3.3改成了time.process_time()
time.asctime([t]) 将一个tuple或struct_time形式的时间(可以通过gmtime()和localtime()方法获取)转换为一个24个字符的时间字符串,格式为: “Fri Aug 19 11:14:16 2016”。如果参数t未提供,则取localtime()的返回值作为参数。
time.ctime([secs]) 功能同上,将一个秒数时间戳表示的时间转换为一个表示当前本地时间的字符串。如果参数secs没有提供或值为None,则取time()方法的返回值作为默认值。ctime(secs)等价于asctime(localtime(secs))
time.time() 返回时间戳(自1970-1-1 0:00:00 至今所经历的秒数)
time.localtime([secs]) 返回以指定时间戳对应的本地时间的 struct_time对象(可以通过下标,也可以通过 .属性名 的方式来引用内部属性)格式
time.localtime(time.time() + n*3600) 返回n个小时后本地时间的 struct_time对象格式(可以用来实现类似crontab的功能)
time.gmtime([secs]) 返回指定时间戳对应的utc时间的 struct_time对象格式(与当前本地时间差8个小时)
time.gmtime(time.time() + n*3600) 返回n个小时后utc时间的 struct_time对象(可以通过 .属性名 的方式来引用内部属性)格式
time.strptime(time_str, time_format_str) 将时间字符串转换为struct_time时间对象,如:time.strptime(‘2017-01-13 17:07’, ‘%Y-%m-%d %H:%M’)
time.mktime(struct_time_instance) 将struct_time对象实例转换成时间戳
time.strftime(time_format_str, struct_time_instance) 将struct_time对象实例转换成字符串

关于time的练习

#获取时间戳
time.time()
>>1527822215.2171364
#获取字符串格式的时间
time.localtime()
>>time.struct_time(tm_year=2018, tm_mon=6, tm_mday=1, tm_hour=11, tm_min=6, tm_sec=39, tm_wday=4, tm_yday=152, tm_isdst=0)
time.gmtime()
>>time.struct_time(tm_year=2018, tm_mon=6, tm_mday=1, tm_hour=11, tm_min=6, tm_sec=39, tm_wday=4, tm_yday=152, tm_isdst=0)

####获取字符串格式的时间######
time.ctime()
>>'Fri Jun  1 11:16:45 2018'
time.asctime()
>>'Fri Jun  1 11:16:45 2018'

########时间戳格式转变成time_struct格式时间#########

t=time.time()
t_1=time.localtime(t)
print(t_1)
>>time.struct_time(tm_year=2018, tm_mon=6, tm_mday=1, tm_hour=12, tm_min=29, tm_sec=47, tm_wday=4, tm_yday=152, tm_isdst=0)

#######字符串格式转struct_time时间格式#########
time.strptime('Sat Feb 04 14:06:42 2017')
time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=14, tm_min=6, tm_sec=42, tm_wday=5, tm_yday=35, tm_isdst=-1)

#********
time.strptime('Sat Feb 04 14:06:42 2017', '%a %b %d %H:%M:%S %Y')
time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=14, tm_min=6, tm_sec=42, tm_wday=5, tm_yday=35, tm_isdst=-1)
#*********
time.strptime('2017-02-04 14:12', '%Y-%m-%d %H:%M')
time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=14, tm_min=12, tm_sec=0, tm_wday=5, tm_yday=35, tm_isdst=-1)
#******
time.strptime('2017/02/04 14:12', '%Y/%m/%d %H:%M')
time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=14, tm_min=12, tm_sec=0, tm_wday=5, tm_yday=35, tm_isdst=-1)
#**********
time.strptime('201702041412', '%Y%m%d%H%M')
time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=14, tm_min=12, tm_sec=0, tm_wday=5, tm_yday=35, tm_isdst=-1)


#########struct_time转变成字符串格式#########
time.strftime('%Y-%m-%d %H:%M', time.localtime())
>>>'2017-02-04 14:19'

###########struct_time格式转时间戳格式时间##########
time.mktime(time.localtime())
>>>1486189282.0

时间格式的转换
这里写图片描述

datetime模块
datetime模块提供了处理日期和时间的类,既有简单的方式,又有复杂的方式。它虽然支持日期和时间算法,但其实现的重点是为输出格式化和操作提供高效的属性提取功能。
1. datetime模块中定义的类

类名称 描述
datetime.date 表示日期,常用的属性有:year, month和day
datetime.time 表示时间,常用属性有:hour, minute, second, microsecond
datetime.datetime 表示日期时间
datetime.timedelta 表示两个date、time、datetime实例之间的时间间隔,分辨率(最小单位)可达到微秒
datetime.tzinfo 时区相关信息对象的抽象基类。它们由datetime和time类使用,以提供自定义时间的而调整。
datetime.timezone Python 3.2中新增的功能,实现tzinfo抽象基类的类,表示与UTC的固定偏移量

需要说明的是:这些类的对象都是不可变的。

类之间的关系:

object
 date
 datetime
 time
 timedelta
 tzinfo
 timezone

2. datetime模块中定义的常量

常量名称 描述
datetime.MINYEAR datetime.date或datetime.datetime对象所允许的年份的最小值,值为1
datetime.MAXYEAR datetime.date或datetime.datetime对象所允许的年份的最大值,只为9999

datetime.date类的定义

class datetime.date(year, month, day)

year, month 和 day都是是必须参数,各参数的取值范围为:

参数名称 取值范围
year [MINYEAR, MAXYEAR]
month [1, 12]
day [1, 指定年份的月份中的天数]

类方法和属性

类方法/属性名称 描述
date.max date对象所能表示的最大日期:9999-12-31
date.min date对象所能表示的最小日志:00001-01-01
date.resoluation date对象表示的日期的最小单位:天
date.today() 返回一个表示当前本地日期的date对象
date.fromtimestamp(timestamp) 根据跟定的时间戳,返回一个date对象

对象方法和属性

对象方法/属性名称 描述
d.year
d.month
d.day
d.replace(year[, month[, day]]) 生成并返回一个新的日期对象,原日期对象不变
d.timetuple() 返回日期对应的time.struct_time对象
d.toordinal() 返回日期是是自 0001-01-01 开始的第多少天
d.weekday() 返回日期是星期几,[0, 6],0表示星期一
d.isoweekday() 返回日期是星期几,[1, 7], 1表示星期一
d.isocalendar() 返回一个元组,格式为:(year, weekday, isoweekday)
d.isoformat() 返回‘YYYY-MM-DD’格式的日期字符串
d.strftime(format) 返回指定格式的日期字符串,与time模块的strftime(format, struct_time)功能相同
import time
from datetime import date
print("date.max:",date.max)
print("date.min:",date.min)
print("date.today():",date.today())#返回的是一个对象
print("date.fromtimestamp(time.time()):",date.fromtimestamp(time.time()))#返回的是一个对象
>>>date.max: 9999-12-31
date.min: 0001-01-01
date.today(): 2018-06-01
date.fromtimestamp(time.time()): 2018-06-01





d=date.today()
print("d.year:",d.year)
print("d.month:",d.month)
print("d.day:",d.day)
print("d.replace(2016):",d.replace(2016))
print("d.replace(2016,3):",d.replace(2016,3))
print("d.replace(2016,3,7):",d.replace(2016,3,7))
print("d.timetuple():",d.timetuple())
print("d.toordinal():",d.toordinal())
print("d.weekday():",d.weekday())
print("d.isoweekday():",d.isoweekday())
print("d.isocalendar():",d.isocalendar())
print("d.isofromat():",d.isoformat())
print("d.strftime():",d.strftime("%Y-%m-%d"))
>>>d.year: 2018
d.month: 6
d.day: 1
d.replace(2016): 2016-06-01
d.replace(2016,3): 2016-03-01
d.replace(2016,3,7): 2016-03-07
d.timetuple(): time.struct_time(tm_year=2018, tm_mon=6, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=152, tm_isdst=-1)
d.toordinal(): 736846
d.weekday(): 4
d.isoweekday(): 5
d.isocalendar(): (2018, 22, 5)
d.isofromat(): 2018-06-01
d.strftime(): 2018-06-01

datetime.time类
hour为必须参数,其他为可选参数。各参数的取值范围为:

参数名称 取值范围
hour [0, 23]
minute [0, 59]
second [0, 59]
microsecond [0, 1000000]
tzinfo tzinfo的子类对象,如timezone类的实例

类方法和属性

类方法/属性名称 描述
time.max time类所能表示的最大时间:time(23, 59, 59, 999999)
time.min time类所能表示的最小时间:time(0, 0, 0, 0)
time.resolution 时间的最小单位,即两个不同时间的最小差值:1微秒

对象方法和属性

对象方法/属性名称 描述
t.hour
t.minute
t.second
t.microsecond 微秒
t.tzinfo 返回传递给time构造方法的tzinfo对象,如果该参数未给出,则返回None
t.replace(hour[, minute[, second[, microsecond[, tzinfo]]]]) 生成并返回一个新的时间对象,原时间对象不变
t.isoformat() 返回一个‘HH:MM:SS.%f’格式的时间字符串
t.strftime() 返回指定格式的时间字符串,与time模块的strftime(format, struct_time)功能相同
from datetime import time
print("time.max:",time.max)
print("time.min:",time.min)
print("time.resolution:",time.resolution)
t = time(20, 5, 40, 8888)
print("t.hour:",t.hour)
print("t.minute:",t.minute)
print("t.second:",t.second)
print("t.microsecond:",t.microsecond)
print("t.replace(19,4):",t.replace(19,4))
print("t.isoformat():",t.isoformat())
print("t.strftime(%H%M%S):",t.strftime("%H%M%S"))
print("t.strftime(%H-%M-%S):",t.strftime("%H-%M-%S"))
print("t.strftime(%H-%M-%S.%f):",t.strftime("%H-%M-%S.%f"))


>>>time.max: 23:59:59.999999
time.min: 00:00:00
time.resolution: 0:00:00.000001
t.hour: 20
t.minute: 5
t.second: 40
t.microsecond: 8888
t.replace(19,4): 19:04:40.008888
t.isoformat(): 20:05:40.008888
t.strftime(%H%M%S): 200540
t.strftime(%H-%M-%S): 20-05-40
t.strftime(%H-%M-%S.%f): 20-05-40.008888

datetime.datetime类
类的定义:

class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)

各参数的取值范围为:

参数名称 取值范围
year [MINYEAR, MAXYEAR]
month [1, 12]
day [1, 指定年份的月份中的天数]
hour [0, 23]
minute [0, 59]
second [0, 59]
microsecond [0, 1000000]
tzinfo tzinfo的子类对象,如timezone类的实例

类方法和属性

类方法/属性名称 描述
datetime.today() 返回一个表示当前本期日期时间的datetime对象
datetime.now([tz]) 返回指定时区日期时间的datetime对象,如果不指定tz参数则结果同上
datetime.utcnow() 返回当前utc日期时间的datetime对象
datetime.fromtimestamp(timestamp[, tz]) 根据指定的时间戳创建一个datetime对象
datetime.utcfromtimestamp(timestamp) 根据指定的时间戳创建一个datetime对象
datetime.combine(date, time) 把指定的date和time对象整合成一个datetime对象
datetime.strptime(date_str, format) 将时间字符串转换为datetime对象

对象方法和属性

对象方法/属性名称 描述
dt.year, dt.month, dt.day 年、月、日
dt.hour, dt.minute, dt.second 时、分、秒
dt.microsecond, dt.tzinfo 微秒、时区信息
dt.date() 获取datetime对象对应的date对象
dt.time() 获取datetime对象对应的time对象, tzinfo 为None
dt.timetz() 获取datetime对象对应的time对象,tzinfo与datetime对象的tzinfo相同
dt.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
dt.timetuple() 返回datetime对象对应的tuple(不包括tzinfo)
dt.utctimetuple() 返回datetime对象对应的utc时间的tuple(不包括tzinfo)
dt.toordinal() 同date对象
dt.weekday() 同date对象
dt.isocalendar() 同date独享
dt.isoformat([sep]) 返回一个‘%Y-%m-%d
dt.ctime() 等价于time模块的time.ctime(time.mktime(d.timetuple()))
dt.strftime(format) 返回指定格式的时间字符串
>>> from datetime import datetime, timezone
>>>
>>> datetime.today()
datetime.datetime(2017, 2, 4, 20, 44, 40, 556318)
>>> datetime.now()
datetime.datetime(2017, 2, 4, 20, 44, 56, 572615)
>>> datetime.now(timezone.utc)
datetime.datetime(2017, 2, 4, 12, 45, 22, 881694, tzinfo=datetime.timezone.utc)
>>> datetime.utcnow()
datetime.datetime(2017, 2, 4, 12, 45, 52, 812508)
>>> import time
>>> datetime.fromtimestamp(time.time())
datetime.datetime(2017, 2, 4, 20, 46, 41, 97578)
>>> datetime.utcfromtimestamp(time.time())
datetime.datetime(2017, 2, 4, 12, 46, 56, 989413)
>>> datetime.combine(date(2017, 2, 4), t)
datetime.datetime(2017, 2, 4, 20, 5, 40, 8888)
>>> datetime.strptime('2017/02/04 20:49', '%Y/%m/%d %H:%M')
datetime.datetime(2017, 2, 4, 20, 49)
>>> dt = datetime.now()
>>> dt
datetime.datetime(2017, 2, 4, 20, 57, 0, 621378)
>>> dt.year
2017
>>> dt.month
2
>>> dt.day
4
>>> dt.hour
20
>>> dt.minute
57
>>> dt.second
0
>>> dt.microsecond
621378
>>> dt.tzinfo
>>> dt.timestamp()
1486213020.621378
>>> dt.date()
datetime.date(2017, 2, 4)
>>> dt.time()
datetime.time(20, 57, 0, 621378)
>>> dt.timetz()
datetime.time(20, 57, 0, 621378)
>>> dt.replace()
datetime.datetime(2017, 2, 4, 20, 57, 0, 621378)
>>> dt.replace(2016)
datetime.datetime(2016, 2, 4, 20, 57, 0, 621378)
>>> dt.timetuple()
time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=20, tm_min=57, tm_sec=0, tm_wday=5, tm_yday=35, tm_isdst=-1)
>>> dt.utctimetuple()
time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=20, tm_min=57, tm_sec=0, tm_wday=5, tm_yday=35, tm_isdst=0)
>>> dt.toordinal()
736364
>>> dt.weekday()
5
>>> dt.isocalendar()
(2017, 5, 6)
>>> dt.isoformat()
'2017-02-04T20:57:00.621378'
>>> dt.isoformat(sep='/')
'2017-02-04/20:57:00.621378'
>>> dt.isoformat(sep=' ')
'2017-02-04 20:57:00.621378'
>>> dt.ctime()
'Sat Feb 4 20:57:00 2017'
>>> dt.strftime('%Y%m%d %H:%M:%S.%f')
'20170204 20:57:00.621378'

如图所示:
这里写图片描述

原文链接

猜你喜欢

转载自blog.csdn.net/the_little_fairy___/article/details/80533287