• day5模块学习 -- time、datetime时间模块


    1、定义

    模块:用来从逻辑上组织python(变量,函数,类,逻辑:实现一个功能)代码,本质就是.py结尾的python文件(文件名:test.py,对应的模块名test)

    包:用来从逻辑上组织模块的,本质就是一个目录(必须带__init__.py文件)

    2、导入方法

    import module_name

    import module1_name,module2_name

    from module_name import *

    from module_alex import logger as logger_alex   '''给模块里面的方法起别名'''

    3、import本质

    导入模块的本质就是把Python文件解释一遍

    导入包的本质就是执行该包下的__init__.py文件

    __file__当前文件的文件名

    4、导入优化

    5、模块的分类

      a.标准库(内置模块)

     b.开源模块

     c.自定义模块

      os模块学习实例链接:http://www.3fwork.com/b204/001543MYM018744/

    time和datetime模块

        time模块

        时间表示形式:"2016-7-18 12:50:36"(格式化的字符串表示方法);2.时间戳表示方式,time.time()(1500415601.3417745),从1970年到现在的秒数;3)元组(struct_time)共九个元素。由于python的time模块实现主要调用C库,所以各个平台可能有所不同。元组形式如下:(time.struct_time(tm_year=2017, tm_mon=7, tm_mday=19, tm_hour=6, tm_min=9, tm_sec=0, tm_wday=2, tm_yday=200, tm_isdst=0)

        在Python中,通常有这几种方式来表示时间:1)时间戳 2)格式化的时间字符串 3)元组(struct_time)共九个元素。由于Python的time模块实现主要调用C库,所以各个平台可能有所不同。

        UTC(Coordinated Universal Time,世界协调时)亦即格林威治天文时间,世界标准时间。在中国为UTC+8。DST(Daylight Saving Time)即夏令时。

        时间戳(timestamp)的方式:通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。返回时间戳方式的函数主要有time(),clock()等。

        元组(struct_time)方式:struct_time元组共有9个元素,返回struct_time的函数主要有gmtime(),localtime(),strptime()。下面列出这种方式元组中的几个元素:

    (time.struct_time(tm_year=2017, tm_mon=7, tm_mday=19, tm_hour=6, tm_min=9, tm_sec=0, tm_wday=2, tm_yday=200, tm_isdst=0)

    索引(Index)属性(Attribute)值(Values)
    1  tm_year(年)  比如2011 
    2  tm_mon(月)  1 - 12
    3  tm_mday(日)  1 - 31
    4  tm_hour(时)  0 - 23
    5  tm_min(分)  0 - 59
    6  tm_sec(秒)  0 - 61
    7  tm_wday(weekday)  0 - 6(0表示周一)
    8  tm_yday(一年中的第几天)  1 - 366
    9  tm_isdst(是否是夏令时)  默认为-1

       time模块

        year (including century, e.g. 1998)
          month (1-12)
          day (1-31)
          hours (0-23)
          minutes (0-59)
          seconds (0-59)
          weekday (0-6, Monday is 0)     0代表星期一
          Julian day (day in the year, 1-366)
          DST (Daylight Savings Time) flag (-1, 0 or 1)

        timezone -- difference in seconds between UTC and local standard time

        返回市区的秒数

        >>> time.timezone
        -28800

        altzone -- difference in  seconds between UTC and local DST time
        daylight -- whether local time should reflect DST

        是否使用夏令时
        tzname -- tuple of (standard time zone name, DST time zone name)

        Functions:
        
        (1)time() -- return current time in seconds since the Epoch as a float    

        返回当前时间的时间戳。

        >>> time.time()
      1500418020.8217583

        下面来看一个例子,运用time.time()来计算函数运行的时间,如下:

    import time
    def calc(first_num,second_num,stop_num):
        '''递归计算斐波那契数列'''
        if first_num == 0:
            print(first_num,second_num)
        third_num = first_num + second_num
        if third_num < stop_num:
            print(third_num)
            calc(second_num,third_num,stop_num)
    
    def calc_time():
        '''计算calc()函数运行的时间'''
        start_time = time.time()
        calc(0,1,10)
        stop_time = time.time()
        run_time = stop_time - start_time
        print(run_time)
    
    calc_time()

        运行结果如下:

      0 1
      1
      2
      3
      5
      8
      0.00010323524475097656

        从上面运行结果可以看出,程序运行的速度还是挺快的,不到一秒时间就运行出来了。

        返回当前时间的时间戳,其实就是时间的秒数表示形式,可以用来计算一个程序执行的时间,如下:


        (2)clock() -- return CPU time since process start as a float      

        这个需要注意,在不同的系统上含义不同。在UNIX系统上,它返回的是“进程时间”,它是用秒表示的浮点数(时间戳)。而在WINDOWS中,第一次调用,返回的是进程运行的实际时间。而第二次之后的调用是自第一次调用以后到现在的运行时间。(实际上是以WIN32上QueryPerformanceCounter()为基础,它比毫秒表示更为精确)


        (3)sleep() -- delay for a number of seconds given as a float   

        线程推迟指定的时间运行。单位为秒

        

    import time
    def calc(arg1,arg2):
        start_time = time.time()
        arg3 = arg1 + arg2
        time.sleep(3)
        stop_time = time.time()
        run_time = stop_time - start_time
        print(run_time)
    
    calc(1,2)
    运行结果如下:
    3.00310945510864

        上面程序就是在程序中插入了time.sleep(3)让程序休眠了3秒,可以看出运行时长增加了,因而当我们写代码的时候,可以添加一些sleep(),给你们老板,完了你们老板说好慢,你说优化一下,把sleep()删除,完了程序确实快了,你们老板对你刮目相看(今天是愚人节)。


        (4)gmtime() -- convert seconds since Epoch to UTC tuple        

        和localtime()方法类似,gmtime()方法是将一个时间戳转换为UTC时区(0时区)的struct_time。

        >>> time.gmtime()
      time.struct_time(tm_year=2017, tm_mon=7, tm_mday=19, tm_hour=12, tm_min=46, tm_sec=12, tm_wday=2, tm_yday=200, tm_isdst=0)
        gmtime()是返回UTC时区的标准时间,我们国家是在东八区,因此会晚8个时区。

        gmtime()如果没有参数,默认是当前系统时间,转换为UTC标准时间

        def gmtime(seconds=None): # real signature unknown; restored from __doc__
        """
        gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,
        tm_sec, tm_wday, tm_yday, tm_isdst)

        Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.
        GMT). When 'seconds' is not passed in, convert the current time instead.

        If the platform supports the tm_gmtoff and tm_zone, they are available as
        attributes only.
        """
        pass

        (5)localtime() -- convert seconds since Epoch to local time tuple

        def localtime(seconds=None): # real signature unknown; restored from __doc__
        """
        localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
        tm_sec,tm_wday,tm_yday,tm_isdst)

        Convert seconds since the Epoch to a time tuple expressing local time.
        When 'seconds' is not passed in, convert the current time instead.
        """
        pass

        将一个时间戳转换为当前时区的struct_time。secs参数未提供,则以当前时间为准

        time.localtime()是转换为当地时间的元组表示形式

        >>> time.localtime()
      time.struct_time(tm_year=2017, tm_mon=7, tm_mday=19, tm_hour=21, tm_min=18, tm_sec=17, tm_wday=2, tm_yday=200, tm_isdst=0)
        提取时间的方式:

    class struct_time(builtins.tuple)
     |  The time value as returned by gmtime(), localtime(), and strptime(), and
     |  accepted by asctime(), mktime() and strftime().  May be considered as a
     |  sequence of 9 integers.
     |  
     |  Note that several fields' values are not the same as those defined by
     |  the C language standard for struct tm.  For example, the value of the
     |  field tm_year is the actual year, not year - 1900.  See individual
     |  fields' descriptions for details.
     |  
     |  Method resolution order:
     |      struct_time
     |      builtins.tuple
     |      builtins.object
     |  
     |  Methods defined here:
     |  
     |  __new__(*args, **kwargs) from builtins.type
     |      Create and return a new object.  See help(type) for accurate signature.
     |  
     |  __reduce__(...)
     |      helper for pickle
     |  
     |  __repr__(self, /)
     |      Return repr(self).
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  tm_gmtoff
     |      offset from UTC in seconds
     |  
     |  tm_hour
     |      hours, range [0, 23]
     |  
     |  tm_isdst
     |      1 if summer time is in effect, 0 if not, and -1 if unknown
     |  
     |  tm_mday
     |      day of month, range [1, 31]
     |  
     |  tm_min
     |      minutes, range [0, 59]
     |  
     |  tm_mon
     |      month of year, range [1, 12]
     |  
     |  tm_sec
     |      seconds, range [0, 61])
     |  
     |  tm_wday
     |      day of week, range [0, 6], Monday is 0
     |  
     |  tm_yday
     |      day of year, range [1, 366]
     |  
     |  tm_year
     |      year, for example, 1993
     |  
     |  tm_zone
     |      abbreviation of timezone name
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  n_fields = 11
     |  
     |  n_sequence_fields = 9
     |  
     |  n_unnamed_fields = 0
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from builtins.tuple:
     |  
     |  __add__(self, value, /)
     |      Return self+value.
     |  
     |  __contains__(self, key, /)
     |      Return key in self.
     |  
     |  __eq__(self, value, /)
     |      Return self==value.
     |  
     |  __ge__(self, value, /)
     |      Return self>=value.
     |  
     |  __getattribute__(self, name, /)
     |      Return getattr(self, name).
     |  
     |  __getitem__(self, key, /)
     |      Return self[key].
     |  
     |  __getnewargs__(...)
     |  
     |  __gt__(self, value, /)
     |      Return self>value.
     |  
     |  __hash__(self, /)
     |      Return hash(self).
     |  
     |  __iter__(self, /)
     |      Implement iter(self).
     |  
     |  __le__(self, value, /)
     |      Return self<=value.
     |  
     |  __len__(self, /)
     |      Return len(self).
     |  
     |  __lt__(self, value, /)
     |      Return self<value.
     |  
     |  __mul__(self, value, /)
     |      Return self*value.n
     |  
     |  __ne__(self, value, /)
     |      Return self!=value.
     |  
     |  __rmul__(self, value, /)
     |      Return self*value.
     |  
     |  count(...)
     |      T.count(value) -> integer -- return number of occurrences of value
     |  
     |  index(...)
     |      T.index(value, [start, [stop]]) -> integer -- return first index of value.
     |      Raises ValueError if the value is not present.
    
    None

       
        (6)asctime() -- convert time tuple to string

    def asctime(p_tuple=None): # real signature unknown; restored from __doc__
        """
        asctime([tuple]) -> string
        
        Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.
        When the time tuple is not present, current time as returned by localtime()
        is used.
        """
        return ""

        把一个表示时间的元组或者struct_time表示为这种形式:'Sun Jun 20 23:21:05 1993'。如果没有参数,将会将time.localtime()作为参数传入。

        >>> x_time = time.localtime()
      >>> x_time.tm_year    #提取年,这个属于属性,而不是方法,tm_year是元组时间的一个属性
      2017
        >>> x_time.tm_min     #分钟数
      26
        >>> x_time.tm_yday   #今年的第几天
      200
        >>> x_time.tm_mday   #当月的第几天
      19
         
        (7)ctime() -- convert time in seconds to string 

        把一个时间戳(按秒计算的浮点数)转化为time.asctime()的形式。如果参数未给或者为None的时候,将会默认time.time()为参数。它的作用相当于time.asctime(time.localtime(secs))。

        >>> time.ctime()
        'Wed Jul 19 22:01:29 2017'

        (8)mktime() -- convert local time tuple to seconds since Epoch

        将一个struct_time转化为时间戳

        将元组形式的时间转化为秒的时间戳,如下所示:

        >>> x = time.localtime()
      >>> x
      time.struct_time(tm_year=2017, tm_mon=7, tm_mday=19, tm_hour=21, tm_min=36, tm_sec=17, tm_wday=2, tm_yday=200, tm_isdst=0)
      >>> time.mktime(x)
      1500471377.0

        (9)strftime() -- convert time tuple to string according to format specification

        把一个代表时间的元组或者struct_time(如由time.localtime()和time.gmtime()返回)转化为格式化的时间字符串。如果t未指定,将传入time.localtime()。如果元组中任何一个元素越界,ValueError的错误将会被抛出。

    def strftime(format, p_tuple=None): # real signature unknown; restored from __doc__
        """
        strftime(format[, tuple]) -> string
        
        Convert a time tuple to a string according to a format specification.
        See the library reference manual for formatting codes. When the time tuple
        is not present, current time as returned by localtime() is used.
        
        Commonly used format codes:
        
        %Y  Year with century as a decimal number.
        %m  Month as a decimal number [01,12].
        %d  Day of the month as a decimal number [01,31].
        %H  Hour (24-hour clock) as a decimal number [00,23].
        %M  Minute as a decimal number [00,59].
        %S  Second as a decimal number [00,61].
        %z  Time zone offset from UTC.
        %a  Locale's abbreviated weekday name.
        %A  Locale's full weekday name.
        %b  Locale's abbreviated month name.
        %B  Locale's full month name.
        %c  Locale's appropriate date and time representation.
        %I  Hour (12-hour clock) as a decimal number [01,12].
        %p  Locale's equivalent of either AM or PM.
        
        Other codes may be available on your platform.  See documentation for
        the C library strftime function.
        """
        return ""
    格式含义备注
    %a 本地(locale)简化星期名称  
    %A 本地完整星期名称  
    %b 本地简化月份名称  
    %B 本地完整月份名称  
    %c 本地相应的日期和时间表示  
    %d 一个月中的第几天(01 - 31)  
    %H 一天中的第几个小时(24小时制,00 - 23)  
    %I 第几个小时(12小时制,01 - 12)  
    %j 一年中的第几天(001 - 366)  
    %m 月份(01 - 12)  
    %M 分钟数(00 - 59)  
    %p 本地am或者pm的相应符
    %S 秒(01 - 61)
    %U 一年中的星期数。(00 - 53星期天是一个星期的开始。)第一个星期天之前的所有天数都放在第0周。
    %w 一个星期中的第几天(0 - 6,0是星期天)
    %W 和%U基本相同,不同的是%W以星期一为一个星期的开始。  
    %x 本地相应日期  
    %X 本地相应时间  
    %y 去掉世纪的年份(00 - 99)  
    %Y 完整的年份  
    %Z 时区的名字(如果不存在为空字符)  
    %% ‘%’字符  

        时间转换的个简写格式:

        %Y  Year with century as a decimal number.
        %m  Month as a decimal number [01,12].
        %d  Day of the month as a decimal number [01,31].
        %H  Hour (24-hour clock) as a decimal number [00,23].
        %M  Minute as a decimal number [00,59].
        %S  Second as a decimal number [00,61].
        %z  Time zone offset from UTC.
        %a  Locale's abbreviated weekday name.
        %A  Locale's full weekday name.
        %b  Locale's abbreviated month name.
        %B  Locale's full month name.
        %c  Locale's appropriate date and time representation.
        %I  Hour (12-hour clock) as a decimal number [01,12].
        %p  Locale's equivalent of either AM or PM.


        (10)strptime() -- parse string to time tuple according to format specification

        把一个格式化时间字符串转化为struct_time。实际上它和strftime()是逆操作。

    def strptime(string, format): # real signature unknown; restored from __doc__
        """
        strptime(string, format) -> struct_time
        
        Parse a string to a time tuple according to a format specification.
        See the library reference manual for formatting codes (same as
        strftime()).
        
        Commonly used format codes:
        
        %Y  Year with century as a decimal number.
        %m  Month as a decimal number [01,12].
        %d  Day of the month as a decimal number [01,31].
        %H  Hour (24-hour clock) as a decimal number [00,23].
        %M  Minute as a decimal number [00,59].
        %S  Second as a decimal number [00,61].
        %z  Time zone offset from UTC.
        %a  Locale's abbreviated weekday name.
        %A  Locale's full weekday name.
        %b  Locale's abbreviated month name.
        %B  Locale's full month name.
        %c  Locale's appropriate date and time representation.
        %I  Hour (12-hour clock) as a decimal number [01,12].
        %p  Locale's equivalent of either AM or PM.
        
        Other codes may be available on your platform.  See documentation for
        the C library strftime function.
        """
        return struct_time
    
    def time(): # real signature unknown; restored from __doc__
        """
        time() -> floating point number
        
        Return the current time in seconds since the Epoch.
        Fractions of a second may be present if the system clock provides them.
        """
        return 0.0

      (11)tzset() -- change the local timezone

       

        datetime模块    (http://www.jb51.net/article/77981.htm)

        Python提供了多个内置模块用于操作日期时间,像calendar,time,datetime。time模块我在之前的文章已经有所介绍,它提供的接口与C标准库time.h基本一致。相比于time模块,datetime模块的接口则更直观、更容易调用。

        1、datetime中包含三个类date ,time,datetime
    函数datetime.combine(date,time)可以得到dateime,datetime.date()、datetime.time()可以获得date和time。

        2.datetime time与sting的转化

        今天就来讲讲datetime模块

        1、datetime模块定义了两个常量:datetime.MINYEAR和datetime.MAXYEAR,分别表示datetime所能表示的最 小、最大年份。其中,MINYEAR = 1,MAXYEAR = 9999。

        2.datetime模块定义了下面这几个类:

       (1)datetime.date:表示日期的类。常用的属性有year,month,day;

       (2)datetime.time:表示时间的类。常用的属性有hour,minute,second,microsecond;

       (3)datetime.datetime:表示日期时间

       (4)datetime.timedelta:表示时间间隔,即两个时间点之间的长度;

       (5)datetime.tzinfo:与时区有关的相关信息

        注:上面这些类型的对象是不可变(immutable)的。

        下面详细介绍这些类使用方式。

        一、date类

        date类表示一个日期。日期由年、月、日组成(地球人都知道)。date类的构造函数如下:

        class datetime.date(year,month,day):参数的意义就不多作解释了,只是这几点要注意一下: 

        >>> today = datetime.date(2017,5,16)
      >>> print(type(today),today)
      <class 'datetime.date'> 2017-05-16
        datetime.date(year,month,day是生成一个日期的类。

        (1)year的范围是[MINYEAR, MAXYEAR],即[1, 9999];

        (2)、month的范围是[1, 12]。(月份是从1开始的,不是从0开始的~_~);

        (3)、day的最大值根据给定的year, month参数来决定。例如闰年2月份有29天;

        date类定义了一些常用的类方法与类属性,方便我们操作:

       (1)、date.max、date.min:date对象所能表示的最大、最小日期;

        >>> datetime.date.max
      datetime.date(9999, 12, 31)
      >>> datetime.date.min
      datetime.date(1, 1, 1)
        最大时间是:9999-12-31,最小时间是:1-1-1

        (2)、date.resolution:date对象表示日期的最小单位。这里是天。

        >>> datetime.date.resolution
      datetime.timedelta(1)
        从上面可以看出,日期最小的表示单位是:天。

        (3)、date.today():返回一个表示当前本地日期的date对象;

        >>> datetime.date.today()
      datetime.date(2017, 7, 19)

        datetime.date.today()返回当天的日期,类似于Excel函数中的today()函数。

        (4)、date.fromtimestamp(timestamp):根据给定的时间戮,返回一个date对象;
        date.fromtimestamp(timestamp):根据给定的时间戮,返回一个date对象;

        import time,datetime
        >>> datetime.date.fromtimestamp(int(time.mktime(time.localtime())))
      datetime.date(2017, 7, 19)

        将一个时间戳转化为date()对象,fromtimestamp(timestamp)

        (5)datetime.fromordinal(ordinal):将Gregorian日历时间转换为date对象;(Gregorian Calendar :一种日历表示方法,类似于我国的农历,西方国家使用比较多,此处不详细展开讨论。)

        date提供的实例方法和属性:

        (1)date.year、date.month、date.day:年、月、日;

        >>> import datetime,time
      >>> dated = datetime.date(2017,8,19)
      >>> dated.year
      2017
      >>> dated.month
      8
      >>> dated.day
      19

        上面例子中,我们定义了一个日期,并且知道了如何提取日期的年、月、日,date.year,date.month,date.day,这些都是日期的属性,而不是方法,因而不需要加括号。

        (2)date.replace(year, month, day):生成一个新的日期对象,用参数指定的年,月,日代替原有对象中的属性。(原有对象仍保持不变)

         >>> dated.replace(year = 2016)
      datetime.date(2016, 8, 19)

      >>> dated.replace(year=2013,month=4,day=2)
      datetime.date(2013, 4, 2)

        上面,我们可以使用date.replace()来更改日期的内容,但是里面是键值对,指明你要修改的是year,month,day中的哪一个。

        (3)date.timetuple():返回日期对应的time.struct_time对象;

        def timetuple(self):
        "Return local time tuple compatible with time.localtime()."
        return _build_struct_time(self._year, self._month, self._day,
        0, 0, 0, -1)

        >>> x = datetime.date.timetuple(datetime.date.today())
      >>> print(x)
      time.struct_time(tm_year=2017, tm_mon=7, tm_mday=20, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=201, tm_isdst=-1)
        可以看出,date.timetuple()返回的是一个元组形式的时间,struct_time,参数是一个日期格式的,date.timetuple(datetime.date)

        (4)date.toordinal():返回日期对应的Gregorian Calendar日期;

        >>> datetime.date.toordinal(datetime.date.today())
      736530

        (5)date.weekday():返回weekday,如果是星期一,返回0;如果是星期2,返回1,以此类推;

        >>> datetime.date.weekday(datetime.date.today())
      3

        date.weekday()是计算星期的,按照国外的方式,0是一周的第一天(周一),3代表周四。

        (6)data.isoweekday():返回weekday,如果是星期一,返回1;如果是星期2,返回2,以此类推;

        >>> datetime.date.isoweekday(datetime.date.today())
      4
        date.isoweekday()就是我们东方人习惯的日期方式,与date.weekday()错开一天。

        (7)date.isocalendar():返回格式如(year,month,day)的元组;

        >>> date.isocalendar(date.today())
      (2017, 29, 4)

        (8)date.isoformat():返回格式如'YYYY-MM-DD'的字符串;

        >>> date.isoformat(date.today())
      '2017-07-20'

        date.isoformat()返回一个日期形式的字符串。

        (9)date.strftime(fmt):自定义格式化字符串。在下面详细讲解.

        >>> now = date(2010,4,6)
      >>> tomorrow = now.replace(day=7)
      >>> print("now:",now,"tomorrow:",tomorrow)
      now: 2010-04-06 tomorrow: 2010-04-07
      >>> print("timetuple()",now.timetuple())
      timetuple() time.struct_time(tm_year=2010, tm_mon=4, tm_mday=6, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1,       tm_yday=96, tm_isdst=-1)
      >>> print("weekday():",now.weekday())
      weekday(): 1
      >>> print("isoweekday():",now.isoweekday())
      isoweekday(): 2
      >>> print("isocalendar():",now.isocalendar())
      isocalendar(): (2010, 14, 2)
      >>> print("isoformat():",now.isoformat())
      isoformat(): 2010-04-06

        date还对某些操作进行了重载,它允许我们对日期进行如下一些操作:

        (1)date2 = date1 + timedelta  # 日期加上一个间隔,返回一个新的日期对象(timedelta将在下面介绍,表示时间间隔);

        (2)date2 = date1 - timedelta   # 日期隔去间隔,返回一个新的日期对象

        (3)timedelta = date1 - date2   # 两个日期相减,返回一个时间间隔对象

        (4)date1 < date2  # 两个日期进行比较

        注: 对日期进行操作时,要防止日期超出它所能表示的范围。
      使用例子:

        >>> now = date.today()
      >>> tomorrow = now.replace(day=22)
      >>> delta = tomorrow - now
      >>> print("now:",now,"tomorrow:",tomorrow)
      now: 2017-07-20 tomorrow: 2017-07-22
      >>> print("timedelta:",delta)
      timedelta: 2 days, 0:00:00
        >>> print(now+delta)
      2017-07-22
      >>> print(tomorrow>now)
      
    True

        二、Time类

        time类表示时间,由时、分、秒以及微秒组成。time类的构造函数如下:

        class datetime.time(hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] ) :各参数的意义不作解释,这里留意一下参数tzinfo,它表示时区信息。注意一下各参数的取值范围:hour的范围为[0, 24),minute的范围为[0, 60),second的范围为[0, 60),microsecond的范围为[0, 1000000)。

         time类定义的类属性:

        (1)time.min、time.max:time类所能表示的最小、最大时间。其中,time.min = time(0, 0, 0, 0), time.max = time(23, 59, 59, 999999);

        >>> time.min
      datetime.time(0, 0)
      >>> time.max
      datetime.time(23, 59, 59, 999999)

        (2)time.resolution:时间的最小单位,这里是1微秒;

        >>> time.resolution
      datetime.timedelta(0, 0, 1)

        time类提供的实例方法和属性:

        (1)time.hour、time.minute、time.second、time.microsecond:时、分、秒、微秒;

        (2)time.tzinfo:时区信息;

        (3)time.replace([ hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] ] ):创建一个新的时间对象,用参数指定的时

    、分、秒、微秒代替原有对象中的属性(原有对象仍保持不变);

        (4)time.isoformat():返回型如"HH:MM:SS"格式的字符串表示;

        (5)time.strftime(fmt):返回自定义格式化字符串。在下面详细介绍;

    from datetime import *
    tm = time(23, 46, 10) 
    print 'tm:', tm 
    print 'hour: %d, minute: %d, second: %d, microsecond: %d'  
        % (tm.hour, tm.minute, tm.second, tm.microsecond) 
    tm1 = tm.replace(hour = 20) 
    print 'tm1:', tm1 
    print 'isoformat():', tm.isoformat() 
      
    # # ---- 结果 ---- 
    # tm: 23:46:10 
    # hour: 23, minute: 46, second: 10, microsecond: 0 
    # tm1: 20:46:10 
    # isoformat(): 23:46:10 

        像date一样,也可以对两个time对象进行比较,或者相减返回一个时间间隔对象。这里就不提供例子了。

        三、datetime类

        datetime是date与time的结合体,包括date与time的所有信息。它的构造函数如下:datetime.datetime (year, month, day[ , hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] ] ),各参数的含义与date、time的构造函数中的一样,要注意参数值的范围。

        datetime类定义的类属性与方法:

        (1)datetime.min、datetime.max:datetime所能表示的最小值与最大值;

        >>> datetime.min
      datetime.datetime(1, 1, 1, 0, 0)
      >>> datetime.max
      datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)

        (2)datetime.resolution:datetime最小单位;

        >>> datetime.resolution
      datetime.timedelta(0, 0, 1)

        (3)datetime.today():返回一个表示当前本地时间的datetime对象;

        >>> datetime.today()
      datetime.datetime(2017, 7, 20, 6, 49, 21, 928607)

        (4)datetime.now([tz]):返回一个表示当前本地时间的datetime对象,如果提供了参数tz,则获取tz参数所指时区的本地时间;

        >>> datetime.now()

      datetime.datetime(2017, 7, 20, 6, 49, 27, 320608)

        now(tz=None) method of builtins.type instance
        Returns new datetime object representing current time local to tz.
        
          tz
            Timezone object.
        
        If no tz is specified, uses local timezone.
        datetime.now([tz])返回一个UTC时区的时间,默认是当前时间。
       

        (5)datetime.utcnow():返回一个当前utc时间的datetime对象;

        >>> datetime.utcnow()
      datetime.datetime(2017, 7, 19, 22, 55, 29, 127130)

        (6)datetime.fromtimestamp(timestamp[, tz]):根据时间戮创建一个datetime对象,参数tz指定时区信息;

        (7)datetime.utcfromtimestamp(timestamp):根据时间戮创建一个datetime对象;

        (8)datetime.combine(date, time):根据date和time,创建一个datetime对象;

        (9)datetime.strptime(date_string, format):将格式字符串转换为datetime对象;

        datetime类提供的实例方法与属性(很多属性或方法在date和time中已经出现过,在此有类似的意义,这里只罗列这些方法名,具体含义不再逐个展开介绍,可以参考上文对date与time类的讲解。)

        (1)datetime.year、month、day、hour、minute、second、microsecond、tzinfo: 

        (2)datetime.date():获取date对象;

      (3)datetime.time():获取time对象;

        (4)datetime. replace ([ year[ , month[ , day[ , hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] ] ] ] ]):

        (5)datetime. timetuple ()

        (6)datetime. utctimetuple ()

        (7)datetime. toordinal ()

        (8)datetime. weekday ()

        (9)datetime. isocalendar ()

        (10)datetime. isoformat ([ sep] )

        (11)datetime. ctime ():返回一个日期时间的C格式字符串,等效于time.ctime(time.mktime(dt.timetuple()));

        (12)datetime. strftime (format)

         像date一样,也可以对两个datetime对象进行比较,或者相减返回一个时间间隔对象,或者日期时间加上一个间隔返回一个新的日期时间对象。这里不提供详细的例子,看客自己动手试一下~~

        四、转化为字符串

        datetime、date、time都提供了strftime()方法,该方法接收一个格式字符串,输出日期时间的字符串表示。下表是从python手册中拉过来的,我对些进行了简单的翻译(翻译的有点噢口~~)。

    格式字符及意义

    %a   星期的简写。如 星期三为Web
    %A   星期的全写。如 星期三为Wednesday
    %b   月份的简写。如4月份为Apr
    %B   月份的全写。如4月份为April
    %c:  日期时间的字符串表示。(如: 04/07/10 10:43:39)
    %d:  日在这个月中的天数(是这个月的第几天)
    %f:  微秒(范围[0,999999])
    %H:  小时(24小时制,[0, 23])
    %I:  小时(12小时制,[0, 11])
    %j:  日在年中的天数 [001,366](是当年的第几天)
    %m:  月份([01,12])
    %M:  分钟([00,59])
    %p:  AM或者PM
    %S:  秒(范围为[00,61],为什么不是[00, 59],参考python手册~_~)
    %U:  周在当年的周数当年的第几周),星期天作为周的第一天
    %w:  今天在这周的天数,范围为[0, 6],6表示星期天
    %W:  周在当年的周数(是当年的第几周),星期一作为周的第一天
    %x:  日期字符串(如:04/07/10)
    %X:  时间字符串(如:10:43:39)
    %y:  2个数字表示的年份
    %Y:  4个数字表示的年份
    %z:  与utc时间的间隔 (如果是本地时间,返回空字符串)
    %Z:  时区名称(如果是本地时间,返回空字符串)
    %%:  %% => %

    dt = datetime.now() 
    print  '(%Y-%m-%d %H:%M:%S %f): ' , dt.strftime( '%Y-%m-%d %H:%M:%S %f' ) 
    print  '(%Y-%m-%d %H:%M:%S %p): ' , dt.strftime( '%y-%m-%d %I:%M:%S %p' ) 
    print  '%%a: %s ' % dt.strftime( '%a' ) 
    print  '%%A: %s ' % dt.strftime( '%A' ) 
    print  '%%b: %s ' % dt.strftime( '%b' ) 
    print  '%%B: %s ' % dt.strftime( '%B' ) 
    print  '日期时间%%c: %s ' % dt.strftime( '%c' ) 
    print  '日期%%x:%s ' % dt.strftime( '%x' ) 
    print  '时间%%X:%s ' % dt.strftime( '%X' ) 
    print  '今天是这周的第%s天 ' % dt.strftime( '%w' ) 
    print  '今天是今年的第%s天 ' % dt.strftime( '%j' ) 
    print  '今周是今年的第%s周 ' % dt.strftime( '%U' ) 
      
    # # ---- 结果 ----  
    # (%Y-%m-%d %H:%M:%S %f): 2010-04-07 10:52:18 937000  
    # (%Y-%m-%d %H:%M:%S %p): 10-04-07 10:52:18 AM  
    # %a: Wed  
    # %A: Wednesday  
    # %b: Apr  
    # %B: April  
    # 日期时间%c: 04/07/10 10:52:18  
    # 日期%x:04/07/10  
    # 时间%X:10:52:18  
    # 今天是这周的第3天  
    # 今天是今年的第097天  
    # 今周是今年的第14周  
    dt = datetime.now() 
    print '(%Y-%m-%d %H:%M:%S %f): ', dt.strftime('%Y-%m-%d %H:%M:%S %f') 
    print '(%Y-%m-%d %H:%M:%S %p): ', dt.strftime('%y-%m-%d %I:%M:%S %p') 
    print '%%a: %s ' % dt.strftime('%a') 
    print '%%A: %s ' % dt.strftime('%A') 
    print '%%b: %s ' % dt.strftime('%b') 
    print '%%B: %s ' % dt.strftime('%B') 
    print '日期时间%%c: %s ' % dt.strftime('%c') 
    print '日期%%x:%s ' % dt.strftime('%x') 
    print '时间%%X:%s ' % dt.strftime('%X') 
    print '今天是这周的第%s天 ' % dt.strftime('%w') 
    print '今天是今年的第%s天 ' % dt.strftime('%j') 
    print '今周是今年的第%s周 ' % dt.strftime('%U') 
      
    # # ---- 结果 ---- 
    # (%Y-%m-%d %H:%M:%S %f): 2010-04-07 10:52:18 937000 
    # (%Y-%m-%d %H:%M:%S %p): 10-04-07 10:52:18 AM 
    # %a: Wed  
    # %A: Wednesday  
    # %b: Apr  
    # %B: April  
    # 日期时间%c: 04/07/10 10:52:18  
    # 日期%x:04/07/10  
    # 时间%X:10:52:18  
    # 今天是这周的第3天  
    # 今天是今年的第097天  
    # 今周是今年的第14周 

    python之time,datetime,string转换

       

    #把datetime转成字符串 
    def datetime_toString(dt): 
      return dt.strftime("%Y-%m-%d-%H") 
      
    #把字符串转成datetime 
    def string_toDatetime(string): 
      return datetime.strptime(string, "%Y-%m-%d-%H") 
      
    #把字符串转成时间戳形式 
    def string_toTimestamp(strTime): 
      return time.mktime(string_toDatetime(strTime).timetuple()) 
      
    #把时间戳转成字符串形式 
    def timestamp_toString(stamp): 
      return time.strftime("%Y-%m-%d-%H", tiem.localtime(stamp)) 
      
    #把datetime类型转外时间戳形式 
    def datetime_toTimestamp(dateTim): 
      return time.mktime(dateTim.timetuple()) 

    以上就是关于python时间模块中的datetime模块的详细介绍,希望对大家的学习有所帮助。

  • 相关阅读:
    致歉
    [公告]博客园正在对网站程序进行性能优化
    [公告]调整默认发布选项
    网站情况继续汇报
    定制“Server Too Busy”错误信息
    可恶的垃圾广告
    博客园分站服务器故障
    很值得期待—SharePoint "V3.0"新特性
    安装Vistual Studio 2005的小问题
    安装智能陈桥五笔时请小心
  • 原文地址:https://www.cnblogs.com/gengcx/p/7163706.html
Copyright © 2020-2023  润新知