【python笔记】python模块 datatime模块
模塊
使用“ import xxx module ”導(dǎo)入模塊的本質(zhì)就是: 將xxxmodule .py 中的全部代碼加載到內(nèi)存井執(zhí)行,然后將整個(gè)模塊內(nèi)容賦值給與模塊同名的變量,該變量的類型是module ,而在該模塊中定義的所有程序單元都相當(dāng)于該module 對(duì)象的成員。
使用from… .import 只導(dǎo)入模塊中部分成員, 該模塊中的輸出
語句也會(huì)在import 時(shí)自動(dòng)執(zhí)行, 這說明Python 依然會(huì)加載并執(zhí)行模塊中的代碼。
在默認(rèn)情況下, 如果使用“from xxx import *”這樣的語句來導(dǎo)入模塊,程序會(huì)導(dǎo)入該模塊中所有不以下畫線開頭的程序單元,
all 變量指定該模塊默認(rèn)只被導(dǎo)入hello 和world 兩個(gè)程序單元:
示例
import TemperatureConversionif __name__ == '__main__':print('32攝氏度 = %.2f華氏度' % TemperatureConversion.c2f(32))print('99華氏度 = %.2f攝氏度' % TemperatureConversion.f2c(99))示例2:
const.py:
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()如果一個(gè) .py 文件(模塊)被直接運(yùn)行時(shí),其__name__值為__main__,即模塊名為__main__。
練習(xí)題:
1、怎么查出通過 from xx import xx導(dǎo)?的可以直接調(diào)?的?法?
通過dir:
import TemperatureConversion
dir(TemperatureConversion)
[‘builtins’, ‘cached’, ‘doc’, ‘file’, ‘loader’, ‘name’, ‘package’, ‘spec’, ‘c2f’, ‘f2c’]
(最后一行是輸出結(jié)果)
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):""" 對(duì)于不存在的元素,返回計(jì)數(shù)器為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):""" 數(shù)量大于等n的所有元素和計(jì)數(shù)器 """'''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):""" 計(jì)數(shù)器中的所有元素,注:此處非所有元素集合,而是包含所有元素集合的迭代器 """'''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):""" 更新計(jì)數(shù)器,其實(shí)就是增加;如果原來沒有,則新建,如果有則加一 """'''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):""" 相減,原來的計(jì)數(shù)器中的每一個(gè)元素的數(shù)量減去后添加的元素的數(shù)量 """'''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):""" 返回一個(gè)元組(類型,元組) """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 中處理日期的標(biāo)準(zhǔn)模塊,它提供了 4 種對(duì)日期和時(shí)間進(jìn)行處理的類:datetime、date、time 和timedelta。
datetime.now(tz=None) 獲取當(dāng)前的日期時(shí)間,輸出順序?yàn)?#xff1a;年、月、日、時(shí)、分、秒、微秒。
datetime.timestamp() 獲取以 1970年1月1日為起點(diǎn)記錄的秒數(shù)。
datetime.fromtimestamp(tz=None) 使用 unixtimestamp 創(chuàng)建一個(gè) 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 對(duì)象。
轉(zhuǎn)化為指定格式:
將給定日期轉(zhuǎn)換為 “mmm-dd, YYYY” 的格式?
輸入
d1 = datetime.date(‘2010-09-28’)
date類
class date:def __init__(self, year, month, day):passdef today(cls):passdate.today() 獲取當(dāng)前日期信息。
if __name__ == '__main__':d = datetime.date(2021, 1, 2)print(d)d = datetime.date.today()print(d)print(type(d))練習(xí)題:
1、假設(shè)你獲取了用戶輸入的日期和時(shí)間如2020-1-21 9:01:30,以及一個(gè)時(shí)區(qū)信息如UTC+5:00,均是str,請(qǐng)編寫一個(gè)函數(shù)將其轉(zhuǎn)換為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
“”"
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
沒時(shí)間寫了,這個(gè)先擱著。
總結(jié)
以上是生活随笔為你收集整理的【python笔记】python模块 datatime模块的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: npm安装vue 解决VUE无法打开图形
- 下一篇: IDEA第一个mybatis程序 myb