Python进阶(二)-初识Python数据元素:字典&时间

来源:互联网 发布:美工外包靠谱吗 编辑:程序博客网 时间:2024/06/04 01:09

Python进阶(二)-初识Python数据元素:字典&时间

3字典

3.1字典简介

  字典(dic dictionary)是除列表之外python中最灵活的内置数据结构类型。 列表是有序的对象结合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。
  字典由键和对应的值组成。字典也被称作关联数组或哈希表。基本语法如下:

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'};

  也可如此创建字典:

dict1 = { 'abc': 456 };dict2 = { 'abc': 123, 98.6: 37 };

  每个键与值必须用冒号隔开(:),每对用逗号分割,整体放在花括号中({})。键必须独一无二,但值则不必;值可以取任何数据类型,但必须是不可变的,如字符串,数或元组。

3.2访问字典里的值

dict = {'name': 'Zara', 'age': 7, 'class': 'First'};print "dict['name']: ", dict['name'];print "dict['age']: ", dict['age'];

3.3修改字典

  向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对。
如下实例:

dict = {'name': 'Zara', 'age': 7, 'class': 'First'};dict["age"]=27; #修改已有键的值dict["school"]="wutong"; #增加新的键/值对print "dict['age']: ", dict['age'];print "dict['school']: ", dict['school'];

3.4删除字典

del dict['name']; # 删除键是'name'的条目dict.clear(); # 清空词典所有条目del dict ; # 删除词典
  • 注意:字典不存在,del会引发一个异常

3.5字典内置函数&方法

cmp(dict1, dict2) #比较两个字典元素。len(dict) #计算字典元素个数,即键的总数。str(dict) #输出字典可打印的字符串表示。type(variable) #返回输入的变量类型,如果变量是字典就返回字典类型。clear() #删除字典内所有元素copy() #返回一个字典的浅复制fromkeys() #创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值get(key, default=None) #返回指定键的值,如果值不在字典中返回default值has_key(key) #如果键在字典dict里返回true,否则返回falseitems() #以列表返回可遍历的(键, 值) 元组数组keys() #以列表返回一个字典所有的键setdefault(key, default=None) #和get()类似, 但如果键不存在于字典中,将会添加键并将值设为defaultupdate(dict2) #把字典dict2的键/值对更新到dict里values() #以列表返回字典中的所有值

4日期和时间

4.1获取当前时间

import time, datetime;localtime = time.localtime(time.time())print "Local current time :", localtime

  说明:time.struct_time(tm_year=2014, tm_mon=3, tm_mday=21, tm_hour=15, tm_min=13, tm_sec=56, tm_wday=4, tm_yday=80, tm_isdst=0)属于struct_time元组,struct_time元组具有如下属性:
这里写图片描述

4.2获取格式化的时间

  可以根据需求选取各种格式,但是最简单的获取可读的时间模式的函数是asctime():

4.2.1日期转换为字符串

  首选:print time.strftime(‘%Y-%m-%d %H:%M:%S’);
  其次:print datetime.datetime.strftime(datetime.datetime.now(), ‘%Y-%m-%d %H:%M:%S’)
  最后:print str(datetime.datetime.now())[:19]

4.2.2字符串转换为日期

expire_time = "2013-05-21 09:50:35"d = datetime.datetime.strptime(expire_time,"%Y-%m-%d %H:%M:%S")print d;

4.2.3获取日期差

oneday = datetime.timedelta(days=1)#今天,2014-03-21today = datetime.date.today()#昨天,2014-03-20yesterday = datetime.date.today() - oneday#明天,2014-03-22tomorrow = datetime.date.today() + oneday#获取今天零点的时间,2014-03-21 00:00:00today_zero_time=datetime.datetime.strftime(today, '%Y-%m-%d %H:%M:%S')#0:00:00.001000 print datetime.timedelta(milliseconds=1), #1毫秒#0:00:01 print datetime.timedelta(seconds=1), #1秒#0:01:00 print datetime.timedelta(minutes=1), #1分钟#1:00:00 print datetime.timedelta(hours=1), #1小时#1 day, 0:00:00 print datetime.timedelta(days=1), #1天#7 days, 0:00:00print datetime.timedelta(weeks=1)

4.2.4获取时间差

#1 day, 0:00:00oneday = datetime.timedelta(days=1)#今天,2014-03-21 16:07:23.943000today_time = datetime.datetime.now()#昨天,2014-03-20 16:07:23.943000yesterday_time = datetime.datetime.now() - oneday#明天,2014-03-22 16:07:23.943000tomorrow_time = datetime.datetime.now() + oneday

  注意时间是浮点数,带毫秒。
  那么要获取当前时间,需要格式化一下:

print datetime.datetime.strftime(today_time, '%Y-%m-%d %H:%M:%S')print datetime.datetime.strftime(yesterday_time, '%Y-%m-%d %H:%M:%S')print datetime.datetime.strftime(tomorrow_time, '%Y-%m-%d %H:%M:%S')

4.2.5获取上个月最后一天

last_month_last_day = datetime.date(datetime.date.today().year,datetime.date.today().month,1)-datetime.timedelta(1)

4.2.6字符串日期格式化为秒数

  返回浮点类型

expire_time = "2013-05-21 09:50:35"d = datetime.datetime.strptime(expire_time,"%Y-%m-%d %H:%M:%S")time_sec_float = time.mktime(d.timetuple())print time_sec_float

4.2.7日期格式化为秒数

  返回浮点类型

d = datetime.date.today()time_sec_float = time.mktime(d.timetuple())print time_sec_float

4.2.8秒数转字符串

time_sec = time.time()print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time_sec))

这里写图片描述
这里写图片描述

9 2
原创粉丝点击