python 在线

961Python 日期和时间

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import time
import calendar


"""
    时间元组(年、月、日、时、分、秒、一周的第几日、一年的第几日、夏令时)
        一周的第几日: 0-6
        一年的第几日: 1-366
        夏令时: -1, 0, 1
"""

"""
    python中时间日期格式化符号:
    ------------------------------------
    %y 两位数的年份表示(00-99)
    %Y 四位数的年份表示(000-9999)
    %m 月份(01-12)
    %d 月内中的一天(0-31)
    %H 24小时制小时数(0-23)
    %I 12小时制小时数(01-12)
    %M 分钟数(00=59)
    %S 秒(00-59)
    %a 本地简化星期名称
    %A 本地完整星期名称
    %b 本地简化的月份名称
    %B 本地完整的月份名称
    %c 本地相应的日期表示和时间表示
    %j 年内的一天(001-366)
    %p 本地A.M.或P.M.的等价符
    %U 一年中的星期数(00-53)星期天为星期的开始
    %w 星期(0-6),星期天为星期的开始
    %W 一年中的星期数(00-53)星期一为星期的开始
    %x 本地相应的日期表示
    %X 本地相应的时间表示
    %Z 当前时区的名称  # 乱码
    %% %号本身
"""


# (1)当前时间戳
# 1538271871.226226
time.time()


# (2)时间戳 → 时间元组,默认为当前时间
# time.struct_time(tm_year=2018, tm_mon=9, tm_mday=3, tm_hour=9, tm_min=4, tm_sec=1, tm_wday=6, tm_yday=246, tm_isdst=0)
time.localtime()
time.localtime(1538271871.226226)


# (3)时间戳 → 可视化时间
# time.ctime(时间戳),默认为当前时间
time.ctime(1538271871.226226)


# (4)时间元组 → 时间戳
# 1538271871
time.mktime((2018, 9, 30, 9, 44, 31, 6, 273, 0))


# (5)时间元组 → 可视化时间
# time.asctime(时间元组),默认为当前时间
time.asctime()
time.asctime((2018, 9, 30, 9, 44, 31, 6, 273, 0))
time.asctime(time.localtime(1538271871.226226))


# (6)时间元组 → 可视化时间(定制)
# time.strftime(要转换成的格式,时间元组)
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())


# (7)可视化时间(定制) → 时间元祖
# time.strptime(时间字符串,时间格式)
print(time.strptime('2018-9-30 11:32:23', '%Y-%m-%d %H:%M:%S'))


# (8)浮点数秒数,用于衡量不同程序的耗时,前后两次调用的时间差
time.clock()

960Python 日期和时间

使用datetime模块来获取当前的日期和时间

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import datetime
i = datetime.datetime.now()
print ("当前的日期和时间是 %s" % i)
print ("ISO格式的日期和时间是 %s" % i.isoformat() )
print ("当前的年份是 %s" %i.year)
print ("当前的月份是 %s" %i.month)
print ("当前的日期是  %s" %i.day)
print ("dd/mm/yyyy 格式是  %s/%s/%s" % (i.day, i.month, i.year) )
print ("当前小时是 %s" %i.hour)
print ("当前分钟是 %s" %i.minute)
print ("当前秒是  %s" %i.second)

959Python 字典(Dictionary)

访问字典里的值的时候,如果直接用 [] 访问,在没有找到对应键的情况下会报错,一个更好的替代方案是用内置的 get 方法来取键值,这时候如果不存在也不会报错。
>>>test = {'key1':'value1','key2':'value2'}
>>>test['key3'] 报错:KeyError:'key3'
>>>test.get('key3') 无输出
>>>test.get('key3','default') 输出'default'

958Python 字典(Dictionary)

在 Python3 里面, dict.has_key() 被移除了。

改成用 in 或者 not in

例如:

>>> dict = {'Name': 'Zara', 'Age': 7}
>>> print ('Height' in dict)
False
>>> print ('Height' not in dict)
True

Ps:用 in 来判断键是否在字典里面,比 not in 要快。

相关文章:Python3 字典 in 操作符

957Python 字典(Dictionary)

字典的键可以使用布尔类型的,True 默认代表 1,False 默认代表 0,如果包含 0 或 1 就无法使用布尔类型:

>>> test = {0:"1", 1:"2", True:"3", False:"4"}
>>> print(test)
{0: '4', 1: '3'}

没有 0 或 1 的情况下:

>>> test = {"a":"1", "b" :"2", True:"3", False:"4"}
>>> print(test)
{'a': '1', True: '3', 'b': '2', False: '4'}