【python笔记】python模块 datatime模块

模块

使用“ 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 TemperatureConversion

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

示例2:
const.py:

PI = 3.14

def 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 bag
    or multiset.  Elements are stored as dictionary keys and their counts
    are 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
    >>> c
    Counter()

    Note:  If a count is set to zero or reduced to zero, it will remain
    in 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.3

    def __init__(self, iterable=None, **kwds):
        '''Create a new, empty Counter object.  And if given, count elements
        from an input iterable.  Or, initialize the count from another mapping
        of 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 KeyError
        return 0

    def most_common(self, n=None):
        """ 数量大于等n的所有元素和计数器 """
        '''List the n most common elements and their counts from the most
        common 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 Smalltalk
        if 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
        >>> product

        Note, if an element's count has been set to zero or is a negative
        number, 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

    @classmethod
    def 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.get
                    for elem, count in iterable.iteritems():
                        self[elem] = self_get(elem, 0) + count
                else:
                    super(Counter, self).update(iterable) # fast path when counter is empty
            else:
                self_get = self.get
                for elem in iterable:
                    self[elem] = self_get(elem, 0) + 1
        if 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 are
        allowed 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.get
            if isinstance(iterable, Mapping):
                for elem, count in iterable.items():
                    self[elem] = self_get(elem, 0) - count
            else:
                for elem in iterable:
                    self[elem] = self_get(elem, 0) - 1
        if 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 NotImplemented
        result = Counter()
        for elem, count in self.items():
            newcount = count + other[elem]
            if newcount > 0:
                result[elem] = newcount
        for elem, count in other.items():
            if elem not in self and count > 0:
                result[elem] = count
        return result

    def __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 NotImplemented
        result = Counter()
        for elem, count in self.items():
            newcount = count - other[elem]
            if newcount > 0:
                result[elem] = newcount
        for elem, count in other.items():
            if elem not in self and count < 0:
                result[elem] = 0 - count
        return result

    def __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 NotImplemented
        result = Counter()
        for elem, count in self.items():
            other_count = other[elem]
            newcount = other_count if count < other_count else count
            if newcount > 0:
                result[elem] = newcount
        for elem, count in other.items():
            if elem not in self and count > 0:
                result[elem] = count
        return result

    def __and__(self, other):
        ''' Intersection is the minimum of corresponding counts.

        >>> Counter('abbb') & Counter('bcc')
        Counter({'b': 1})

        '''
        if not isinstance(other, Counter):
            return NotImplemented
        result = Counter()
        for elem, count in self.items():
            other_count = other[elem]
            newcount = count if count < other_count else other_count
            if newcount > 0:
                result[elem] = newcount
        return result

    def __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] = count
        return result

    def __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 - count
        return result

    def _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 self

    def __iadd__(self, other):
        '''Inplace add from another counter, keeping only positive counts.

        >>> c = Counter('abbb')
        >>> c += Counter('bcc')
        >>> c
        Counter({'b': 4, 'c': 2, 'a': 1})

        '''
        for elem, count in other.items():
            self[elem] += count
        return self._keep_positive()

    def __isub__(self, other):
        '''Inplace subtract counter, but keep only results with positive counts.

        >>> c = Counter('abbbc')
        >>> c -= Counter('bccd')
        >>> c
        Counter({'b': 2, 'a': 1})

        '''
        for elem, count in other.items():
            self[elem] -= count
        return self._keep_positive()

    def __ior__(self, other):
        '''Inplace union is the maximum of value from either counter.

        >>> c = Counter('abbb')
        >>> c |= Counter('bcc')
        >>> c
        Counter({'b': 3, 'c': 2, 'a': 1})

        '''
        for elem, other_count in other.items():
            count = self[elem]
            if other_count > count:
                self[elem] = other_count
        return self._keep_positive()

    def __iand__(self, other):
        '''Inplace intersection is the minimum of corresponding counts.

        >>> c = Counter('abbb')
        >>> c &= Counter('bcc')
        >>> c
        Counter({'b': 1})

        '''
        for elem, count in self.items():
            other_count = other[elem]
            if other_count < count:
                self[elem] = other_count
        return 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 collections

def 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:59
    print(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):
        pass
    def 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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值