模块

使用“ import xxx module ”导入模块的本质就是: 将xxxmodule .py 中的全部代码加载到内存井执行,然后将整个模块内容赋值给与模块同名的变量,该变量的类型是module ,而在该模块中定义的所有程序单元都相当于该module 对象的成员。
使用from… .import 只导入模块中部分成员, 该模块中的输出
语句也会在import 时自动执行, 这说明Python 依然会加载并执行模块中的代码。

在默认情况下, 如果使用“from xxx import *”这样的语句来导入模块,程序会导入该模块中所有不以下画线开头的程序单元,
all 变量指定该模块默认只被导入hello 和world 两个程序单元:

def hello () :
print ( "Hello, Python")
def world() :
print (" Python World is funny")
def test () :
print ( '-- test 一- ' )
#定义_ all _变量,默认只导入hello 和world 两个程序单元
__all__ =['hell0',' world ']
#导入all module 模块中所有的成员
from all_module import *
test()#此时会显示找不到test

示例

import TemperatureConversionif __name__ == '__main__':print('32摄氏度 = %.2f华氏度' % TemperatureConversion.c2f(32))print('99华氏度 = %.2f摄氏度' % TemperatureConversion.f2c(99))

示例2:
const.py:

PI = 3.14def main():print("PI:", PI)
main()

area.py

from const import PI
def calc_round_area(radius):return PI * (radius ** 2)def main():print("round area: ", calc_round_area(2))main()

如果一个 .py 文件(模块)被直接运行时,其__name__值为__main__,即模块名为__main__。

练习题:

1、怎么查出通过 from xx import xx导⼊的可以直接调⽤的⽅法?

通过dir:

import TemperatureConversion
dir(TemperatureConversion)
[‘builtins’, ‘cached’, ‘doc’, ‘file’, ‘loader’, ‘name’, ‘package’, ‘spec’, ‘c2f’, ‘f2c’]

(最后一行是输出结果)
2、了解Collection模块,编写程序以查询给定列表中最常见的元素。

先贴此模块的方法源代码:

class Counter(dict):'''Dict subclass for counting hashable items.  Sometimes called a bagor multiset.  Elements are stored as dictionary keys and their countsare stored as dictionary values.>>> c = Counter('abcdeabcdabcaba')  # count elements from a string>>> c.most_common(3)                # three most common elements[('a', 5), ('b', 4), ('c', 3)]>>> sorted(c)                       # list all unique elements['a', 'b', 'c', 'd', 'e']>>> ''.join(sorted(c.elements()))   # list elements with repetitions'aaaaabbbbcccdde'>>> sum(c.values())                 # total of all counts>>> c['a']                          # count of letter 'a'>>> for elem in 'shazam':           # update counts from an iterable...     c[elem] += 1                # by adding 1 to each element's count>>> c['a']                          # now there are seven 'a'>>> del c['b']                      # remove all 'b'>>> c['b']                          # now there are zero 'b'>>> d = Counter('simsalabim')       # make another counter>>> c.update(d)                     # add in the second counter>>> c['a']                          # now there are nine 'a'>>> c.clear()                       # empty the counter>>> cCounter()Note:  If a count is set to zero or reduced to zero, it will remainin the counter until the entry is deleted or the counter is cleared:>>> c = Counter('aaabbc')>>> c['b'] -= 2                     # reduce the count of 'b' by two>>> c.most_common()                 # 'b' is still in, but its count is zero[('a', 3), ('c', 1), ('b', 0)]'''# References:#   http://en.wikipedia.org/wiki/Multiset#   http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html#   http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm#   http://code.activestate.com/recipes/259174/#   Knuth, TAOCP Vol. II section 4.6.3def __init__(self, iterable=None, **kwds):'''Create a new, empty Counter object.  And if given, count elementsfrom an input iterable.  Or, initialize the count from another mappingof elements to their counts.>>> c = Counter()                           # a new, empty counter>>> c = Counter('gallahad')                 # a new counter from an iterable>>> c = Counter({'a': 4, 'b': 2})           # a new counter from a mapping>>> c = Counter(a=4, b=2)                   # a new counter from keyword args'''super(Counter, self).__init__()self.update(iterable, **kwds)def __missing__(self, key):""" 对于不存在的元素,返回计数器为0 """'The count of elements not in the Counter is zero.'# Needed so that self[missing_item] does not raise KeyErrorreturn 0def most_common(self, n=None):""" 数量大于等n的所有元素和计数器 """'''List the n most common elements and their counts from the mostcommon to the least.  If n is None, then list all element counts.>>> Counter('abcdeabcdabcaba').most_common(3)[('a', 5), ('b', 4), ('c', 3)]'''# Emulate Bag.sortedByCount from Smalltalkif n is None:return sorted(self.iteritems(), key=_itemgetter(1), reverse=True)return _heapq.nlargest(n, self.iteritems(), key=_itemgetter(1))def elements(self):""" 计数器中的所有元素,注:此处非所有元素集合,而是包含所有元素集合的迭代器 """'''Iterator over elements repeating each as many times as its count.>>> c = Counter('ABCABC')>>> sorted(c.elements())['A', 'A', 'B', 'B', 'C', 'C']# Knuth's example for prime factors of 1836:  2**2 * 3**3 * 17**1>>> prime_factors = Counter({2: 2, 3: 3, 17: 1})>>> product = 1>>> for factor in prime_factors.elements():     # loop over factors...     product *= factor                       # and multiply them>>> productNote, if an element's count has been set to zero or is a negativenumber, elements() will ignore it.'''# Emulate Bag.do from Smalltalk and Multiset.begin from C++.return _chain.from_iterable(_starmap(_repeat, self.iteritems()))# Override dict methods where necessary@classmethoddef fromkeys(cls, iterable, v=None):# There is no equivalent method for counters because setting v=1# means that no element can have a count greater than one.raise NotImplementedError('Counter.fromkeys() is undefined.  Use Counter(iterable) instead.')def update(self, iterable=None, **kwds):""" 更新计数器,其实就是增加;如果原来没有,则新建,如果有则加一 """'''Like dict.update() but add counts instead of replacing them.Source can be an iterable, a dictionary, or another Counter instance.>>> c = Counter('which')>>> c.update('witch')           # add elements from another iterable>>> d = Counter('watch')>>> c.update(d)                 # add elements from another counter>>> c['h']                      # four 'h' in which, witch, and watch'''# The regular dict.update() operation makes no sense here because the# replace behavior results in the some of original untouched counts# being mixed-in with all of the other counts for a mismash that# doesn't have a straight-forward interpretation in most counting# contexts.  Instead, we implement straight-addition.  Both the inputs# and outputs are allowed to contain zero and negative counts.if iterable is not None:if isinstance(iterable, Mapping):if self:self_get = self.getfor elem, count in iterable.iteritems():self[elem] = self_get(elem, 0) + countelse:super(Counter, self).update(iterable) # fast path when counter is emptyelse:self_get = self.getfor elem in iterable:self[elem] = self_get(elem, 0) + 1if kwds:self.update(kwds)def subtract(self, iterable=None, **kwds):""" 相减,原来的计数器中的每一个元素的数量减去后添加的元素的数量 """'''Like dict.update() but subtracts counts instead of replacing them.Counts can be reduced below zero.  Both the inputs and outputs areallowed to contain zero and negative counts.Source can be an iterable, a dictionary, or another Counter instance.>>> c = Counter('which')>>> c.subtract('witch')             # subtract elements from another iterable>>> c.subtract(Counter('watch'))    # subtract elements from another counter>>> c['h']                          # 2 in which, minus 1 in witch, minus 1 in watch>>> c['w']                          # 1 in which, minus 1 in witch, minus 1 in watch-1'''if iterable is not None:self_get = self.getif isinstance(iterable, Mapping):for elem, count in iterable.items():self[elem] = self_get(elem, 0) - countelse:for elem in iterable:self[elem] = self_get(elem, 0) - 1if kwds:self.subtract(kwds)def copy(self):""" 拷贝 """'Return a shallow copy.'return self.__class__(self)def __reduce__(self):""" 返回一个元组(类型,元组) """return self.__class__, (dict(self),)def __delitem__(self, elem):""" 删除元素 """'Like dict.__delitem__() but does not raise KeyError for missing values.'if elem in self:super(Counter, self).__delitem__(elem)def __repr__(self):if not self:return '%s()' % self.__class__.__name__items = ', '.join(map('%r: %r'.__mod__, self.most_common()))return '%s({%s})' % (self.__class__.__name__, items)# Multiset-style mathematical operations discussed in:#       Knuth TAOCP Volume II section 4.6.3 exercise 19#       and at http://en.wikipedia.org/wiki/Multiset## Outputs guaranteed to only include positive counts.## To strip negative and zero counts, add-in an empty counter:#       c += Counter()def __add__(self, other):'''Add counts from two counters.>>> Counter('abbb') + Counter('bcc')Counter({'b': 4, 'c': 2, 'a': 1})'''if not isinstance(other, Counter):return NotImplementedresult = Counter()for elem, count in self.items():newcount = count + other[elem]if newcount > 0:result[elem] = newcountfor elem, count in other.items():if elem not in self and count > 0:result[elem] = countreturn resultdef __sub__(self, other):''' Subtract count, but keep only results with positive counts.>>> Counter('abbbc') - Counter('bccd')Counter({'b': 2, 'a': 1})'''if not isinstance(other, Counter):return NotImplementedresult = Counter()for elem, count in self.items():newcount = count - other[elem]if newcount > 0:result[elem] = newcountfor elem, count in other.items():if elem not in self and count < 0:result[elem] = 0 - countreturn resultdef __or__(self, other):'''Union is the maximum of value in either of the input counters.>>> Counter('abbb') | Counter('bcc')Counter({'b': 3, 'c': 2, 'a': 1})'''if not isinstance(other, Counter):return NotImplementedresult = Counter()for elem, count in self.items():other_count = other[elem]newcount = other_count if count < other_count else countif newcount > 0:result[elem] = newcountfor elem, count in other.items():if elem not in self and count > 0:result[elem] = countreturn resultdef __and__(self, other):''' Intersection is the minimum of corresponding counts.>>> Counter('abbb') & Counter('bcc')Counter({'b': 1})'''if not isinstance(other, Counter):return NotImplementedresult = Counter()for elem, count in self.items():other_count = other[elem]newcount = count if count < other_count else other_countif newcount > 0:result[elem] = newcountreturn resultdef __pos__(self):'Adds an empty counter, effectively stripping negative and zero counts'result = Counter()for elem, count in self.items():if count > 0:result[elem] = countreturn resultdef __neg__(self):'''Subtracts from an empty counter.  Strips positive and zero counts,and flips the sign on negative counts.'''result = Counter()for elem, count in self.items():if count < 0:result[elem] = 0 - countreturn resultdef _keep_positive(self):'''Internal method to strip elements with a negative or zero count'''nonpositive = [elem for elem, count in self.items() if not count > 0]for elem in nonpositive:del self[elem]return selfdef __iadd__(self, other):'''Inplace add from another counter, keeping only positive counts.>>> c = Counter('abbb')>>> c += Counter('bcc')>>> cCounter({'b': 4, 'c': 2, 'a': 1})'''for elem, count in other.items():self[elem] += countreturn self._keep_positive()def __isub__(self, other):'''Inplace subtract counter, but keep only results with positive counts.>>> c = Counter('abbbc')>>> c -= Counter('bccd')>>> cCounter({'b': 2, 'a': 1})'''for elem, count in other.items():self[elem] -= countreturn self._keep_positive()def __ior__(self, other):'''Inplace union is the maximum of value from either counter.>>> c = Counter('abbb')>>> c |= Counter('bcc')>>> cCounter({'b': 3, 'c': 2, 'a': 1})'''for elem, other_count in other.items():count = self[elem]if other_count > count:self[elem] = other_countreturn self._keep_positive()def __iand__(self, other):'''Inplace intersection is the minimum of corresponding counts.>>> c = Counter('abbb')>>> c &= Counter('bcc')>>> cCounter({'b': 1})'''for elem, count in self.items():other_count = other[elem]if other_count < count:self[elem] = other_countreturn self._keep_positive()

题目说明:

输入:language = [‘PHP’, ‘PHP’, ‘Python’, ‘PHP’, ‘Python’, ‘JS’, ‘Python’, ‘Python’,‘PHP’, ‘Python’]

输出:Python

“”"
Input file
language = [‘PHP’, ‘PHP’, ‘Python’, ‘PHP’, ‘Python’, ‘JS’, ‘Python’, ‘Python’,‘PHP’, ‘Python’]

Output file
Python
“”"
def most_element(language):
“”" Return a list of lines after inserting a word in a specific line. “”"

----答:

import collectionsdef most_element(languagee):x = collections.Counter(languagee)len1 = len(x)top = x.most_common(1)[0][0]print(top)if __name__ == '__main__':language = collections.deque(['PHP', 'PHP', 'Python', 'PHP', 'Python', 'JS', 'Python', 'Python', 'PHP', 'Python'])most_element(language)

输出python

datatime模块

datetime 是 Python 中处理日期的标准模块,它提供了 4 种对日期和时间进行处理的类:datetime、date、time 和timedelta。
datetime.now(tz=None) 获取当前的日期时间,输出顺序为:年、月、日、时、分、秒、微秒。
datetime.timestamp() 获取以 1970年1月1日为起点记录的秒数。
datetime.fromtimestamp(tz=None) 使用 unixtimestamp 创建一个 datetime。

示例

if __name__ == '__main__':tt = datetime.datetime.now()print(tt)dt = datetime.datetime(year=2021, month=2, day=1, hour=11, minute=23, second=59)print(dt)  # 2020-06-25 11:23:59print(dt.timestamp())  # 1593055439.0

输出:
2021-02-02 16:02:42.119566
2021-02-01 11:23:59
1612149839.0

Process finished with exit code 0

datetime.strftime(fmt) 格式化 datetime 对象。
转化为指定格式:

if __name__ == '__main__':dt = datetime.datetime(year=2021, month=2, day=1, hour=15, minute=51, second=49)s = dt.strftime("'%Y/%m/%d %H:%M:%S")print(s)s = dt.strftime('%d %B, %Y, %A')print(s)

将给定日期转换为 “mmm-dd, YYYY” 的格式?

输入
d1 = datetime.date(‘2010-09-28’)

date类

class date:def __init__(self, year, month, day):passdef today(cls):pass

date.today() 获取当前日期信息。

if __name__ == '__main__':d = datetime.date(2021, 1, 2)print(d)d = datetime.date.today()print(d)print(type(d))

练习题:

1、假设你获取了用户输入的日期和时间如2020-1-21 9:01:30,以及一个时区信息如UTC+5:00,均是str,请编写一个函数将其转换为timestamp:

题目说明:

“”"

Input file
example1: dt_str=‘2020-6-1 08:10:30’, tz_str=‘UTC+7:00’
example2: dt_str=‘2020-5-31 16:10:30’, tz_str=‘UTC-09:00’

Output file
result1: 1590973830.0
result2: 1590973830.0
“”"

from datetime import datetime, timezone, timedelta
def trans():dtstr = input("pleas 输入时间:")dtstr2 = input("输入时区:")dtstr2 = dtstr2.split(':')[0].split('+')dtstr = datetime.strptime(dtstr, '%Y-%m-%d %H:%M:%S')utc_dt = dtstr.replace(tzinfo=timezone(timedelta(hours=int(dtstr2[1]))))return utc_dt.timestamp()if __name__ == '__main__':print(trans())

2、编写Python程序以选择指定年份的所有星期日。

题目说明:

“”"

Input file
2020

Output file
2020-01-05
2020-01-12
2020-01-19
2020-01-26
2020-02-02

2020-12-06
2020-12-13
2020-12-20
2020-12-27
“”"

def all_sundays(year):
# your code here

没时间写了,这个先搁着。

【python笔记】python模块 datatime模块相关推荐

  1. Python笔记 - Python切片

    Python笔记 - Python切片 Python切片是对一个列表取其部分元素获得一个子序列的常见操作,切片操作的返回结果类型与被切片的对象一致.要创建一个已有列表的切片,通过指定切片的第一个列表元 ...

  2. Python笔记之通过PyWin32模块实现在QQ聊天窗口自动发送消息

    文章目录 PyWin32模块 简介 安装 帮助文档 程序代码 调用的函数 1. win32clipboard.SetClipboardData(format, hMem) 作用 参数 返回值 2. w ...

  3. 第四周python笔记 Python封装结构 哈希查找 杨辉三角 冒泡排序

    知识点:浅拷贝 字符串  封装解构 集合 ipython 哈希查找与线性查找  代码实现:杨辉三角 冒泡排序 list复制 是浅拷贝 简单类型 新开地址 拷贝数值 引用类型 只拷贝引用 直接拷贝地址 ...

  4. 【Python笔记】使用 re 模块实现正则表达式操作

    使用 re 模块实现正则表达式操作 匹配字符串 使用 match() 方法进行匹配 使用 search() 方法进行匹配 使用 findall() 方法进行匹配 替换字符串 使用正则表达式分割字符串 ...

  5. Python笔记:利用pygame模块实现三原色颜色滚动条效果

    import pygame from pygame.locals import * from sys import exit def create_scales(height):#用于创建指定大小的图 ...

  6. python笔记-python编程优化:常用原则和技术介绍

    本人翻译自<Exper Python Programming> 'Premature optimization is the root of all evil in programming ...

  7. Python笔记 · Python语言的“动态性”

    尽管对于Python程序员来说已经司空见惯,但是当那些从非动态语言转过来的程序员初次看到形如self.xxx=xxx的语句就是在定义对象属性时往往会感到"离奇":一个未经声明的(类 ...

  8. python中的时间处理模块(二):datetime模块之timedelta类详解

    1.datetime模块   datatime模块是在time模块的基础之上做了封装,提供了更多更好用的类供我们使用,常用的有date.time.datetime.timedelta.tzinfo.但 ...

  9. Python学习笔记——time模块和datatime模块【时间处理】

    例子 time模块: import timet1 = time.time()#返回当前时间 t2 = time.localtime()#返回本地时间以元组的形式表示 t3 = time.asctime ...

最新文章

  1. 兀键和6键怎么判断_化学干货II高中化学分子或离子中的大π键如何判断?
  2. doT.js灵活运用之嵌入使用
  3. 虚拟现实大会ChinaVR2015报告之-From Visual Content to Virtual Reality Data-driven Intelligence Production
  4. 递归 反转字符串_使用递归反转字符串
  5. Linux linux下的进程状态
  6. mysql在windows启动_MySQL笔记:mySQL在windows环境启动
  7. Eclipse创建web项目
  8. Web前端大作业——城旅游景点介绍(HTML+CSS+JavaScript) html旅游网站设计与实现
  9. 国内智能手机市场寒风凛冽,华米OV谁更受伤?
  10. python画图旋转图形_python简单实现旋转图片的方法
  11. Glide 的 transformation
  12. 一句代码让电脑定时重启,关机,取消关机
  13. 概念模型、逻辑模型和物理模型的区别
  14. java中的并发错误和死锁
  15. IM开发者的零基础通信技术入门(一):通信交换技术的百年发展史(上)
  16. 计算三个经纬度坐标的夹角
  17. 电脑关机蓝屏,然后自动重启的问题解决。
  18. 解决笔记本电脑突然搜不到可用网络
  19. Win11:无法枚举容器中的对象 访问被拒绝
  20. 【C++】多继承的多态

热门文章

  1. 链表实现c语言通讯录管理系统,C++链表实现通讯录管理系统.pdf
  2. stanford course
  3. android 启动另外一个activity,起动另外一个activity只能在activity里面启动吗
  4. 计算机二级c选择题题库,C程序设计选择题题库【2018计算机二级考试题库:《C++》选择题练习】...
  5. kotlin将对象转换为map_在 Kotlin 的 data class 中使用 MapStruct
  6. 四十四、深入Java 的序列化和反序列化
  7. 10万奖金!探索图像盲降噪新方式,旷视2022 MegCup炼丹大赛等你来战
  8. Python 和 C/C++ 拓展程序的性能优化
  9. 直播 | 达观数据高级技术专家杨慧宇:金融数据结构化实践
  10. 30万奖金等你拿 | “信也科技杯”第五届数据解决方案应用大赛火热报名中!...