Python学习之time模块(十)

time模块提供了各种与时间有关的功能,想了解该模块的详细信息的可以参考官方的文档:

https://docs.python.org/3/library/time.html

在这里,主要总结下time模块各个方法的使用,和常用功能的实现过程,首先我们来看time模块中各个方法的详细的信息,见time模块中各个类以及方法的源码,见如下的内容:

# encoding: utf-8
# module time
# from (built-in)
# by generator 1.145
"""
This module provides various functions to manipulate time values.

There are two standard representations of time.  One is the number
of seconds since the Epoch, in UTC (a.k.a. GMT).  It may be an integer
or a floating point number (to represent fractions of seconds).
The Epoch is system-defined; on Unix, it is generally January 1st, 1970.
The actual value can be retrieved by calling gmtime(0).

The other representation is a tuple of 9 integers giving local time.
The tuple items are:
  year (four digits, e.g. 1998)
  month (1-12)
  day (1-31)
  hours (0-23)
  minutes (0-59)
  seconds (0-59)
  weekday (0-6, Monday is 0)
  Julian day (day in the year, 1-366)
  DST (Daylight Savings Time) flag (-1, 0 or 1)
If the DST flag is 0, the time is given in the regular time zone;
if it is 1, the time is given in the DST time zone;
if it is -1, mktime() should guess based on the date and time.

Variables:

timezone -- difference in seconds between UTC and local standard time
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:

time() -- return current time in seconds since the Epoch as a float
clock() -- return CPU time since process start as a float
sleep() -- delay for a number of seconds given as a float
gmtime() -- convert seconds since Epoch to UTC tuple
localtime() -- convert seconds since Epoch to local time tuple
asctime() -- convert time tuple to string
ctime() -- convert time in seconds to string
mktime() -- convert local time tuple to seconds since Epoch
strftime() -- convert time tuple to string according to format specification
strptime() -- parse string to time tuple according to format specification
tzset() -- change the local timezone
"""
# no imports

# Variables with simple values

accept2dyear = 1

altzone = -32400

daylight = 0

timezone = -28800

# functions

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 ""

def clock(): # real signature unknown; restored from __doc__
    """
    clock() -> floating point number
    
    Return the CPU time or real time since the start of the process or since
    the first call to clock().  This has as much precision as the system
    records.
    """
    return 0.0

def ctime(seconds=None): # known case of time.ctime
    """
    ctime(seconds) -> string
    
    Convert a time in seconds since the Epoch to a string in local time.
    This is equivalent to asctime(localtime(seconds)). When the time tuple is
    not present, current time as returned by localtime() is used.
    """
    return ""

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.
    """
    pass

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

def mktime(p_tuple): # real signature unknown; restored from __doc__
    """
    mktime(tuple) -> floating point number
    
    Convert a time tuple in local time to seconds since the Epoch.
    """
    return 0.0

def sleep(seconds): # real signature unknown; restored from __doc__
    """
    sleep(seconds)
    
    Delay execution for a given number of seconds.  The argument may be
    a floating point number for subsecond precision.
    """
    pass

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.
    """
    return ""

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()).
    """
    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

# classes

class struct_time(object):
    """
    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.
    """
    def __add__(self, y): # real signature unknown; restored from __doc__
        """ x.__add__(y) <==> x+y """
        pass

    def __contains__(self, y): # real signature unknown; restored from __doc__
        """ x.__contains__(y) <==> y in x """
        pass

    def __eq__(self, y): # real signature unknown; restored from __doc__
        """ x.__eq__(y) <==> x==y """
        pass

    def __getitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __getslice__(self, i, j): # real signature unknown; restored from __doc__
        """
        x.__getslice__(i, j) <==> x[i:j]
                   
                   Use of negative indices is not supported.
        """
        pass

    def __ge__(self, y): # real signature unknown; restored from __doc__
        """ x.__ge__(y) <==> x>=y """
        pass

    def __gt__(self, y): # real signature unknown; restored from __doc__
        """ x.__gt__(y) <==> x>y """
        pass

    def __hash__(self): # real signature unknown; restored from __doc__
        """ x.__hash__() <==> hash(x) """
        pass

    def __init__(self, *args, **kwargs): # real signature unknown
        pass

    def __len__(self): # real signature unknown; restored from __doc__
        """ x.__len__() <==> len(x) """
        pass

    def __le__(self, y): # real signature unknown; restored from __doc__
        """ x.__le__(y) <==> x<=y """
        pass

    def __lt__(self, y): # real signature unknown; restored from __doc__
        """ x.__lt__(y) <==> x<y """
        pass

    def __mul__(self, n): # real signature unknown; restored from __doc__
        """ x.__mul__(n) <==> x*n """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more): # real signature unknown; restored from __doc__
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __ne__(self, y): # real signature unknown; restored from __doc__
        """ x.__ne__(y) <==> x!=y """
        pass

    def __reduce__(self, *args, **kwargs): # real signature unknown
        pass

    def __repr__(self): # real signature unknown; restored from __doc__
        """ x.__repr__() <==> repr(x) """
        pass

    def __rmul__(self, n): # real signature unknown; restored from __doc__
        """ x.__rmul__(n) <==> n*x """
        pass

    tm_hour = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """hours, range [0, 23]"""

    tm_isdst = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """1 if summer time is in effect, 0 if not, and -1 if unknown"""

    tm_mday = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """day of month, range [1, 31]"""

    tm_min = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """minutes, range [0, 59]"""

    tm_mon = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """month of year, range [1, 12]"""

    tm_sec = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """seconds, range [0, 61])"""

    tm_wday = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """day of week, range [0, 6], Monday is 0"""

    tm_yday = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """day of year, range [1, 366]"""

    tm_year = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """year, for example, 1993"""


    n_fields = 9
    n_sequence_fields = 9
    n_unnamed_fields = 0


# variables with complex values

tzname = (
    '\xd6\xd0\xb9\xfa\xb1\xea\xd7\xbc\xca\xb1\xbc\xe4',
    '\xd6\xd0\xb9\xfa\xcf\xc4\xc1\xee\xca\xb1',
)

下面我们逐步的来看time模块中各个方法的具体使用,具体见如下的案例代码:

#!/usr/bin/env python 
# -*- coding:utf-8 -*-


import  time

print u'休眠二秒打印出hello world,开始倒计时...'
time.sleep(2)
print 'hello world'

#获取时间戳(1970年开始计时的)
print u'获取时间戳:',time.time()

print u'返回当前日期的字符串格式:\n',time.ctime()

print u'时间戳转为字符串:\n',time.ctime(time.time())

print u'时间戳转为struct_time格式:\n',time.gmtime(time.time())

time_gmtime=time.gmtime(time.time())
print u'查看struct_time格式的显示年月日时分秒结果:\n',\
   str(time_gmtime.tm_year)+'-'+\
   str(time_gmtime.tm_mon)+'-'+\
   str(time_gmtime.tm_mday)+' '+\
   str(time_gmtime.tm_hour)+':'+\
   str(time_gmtime.tm_min)+':'+\
   str(time_gmtime.tm_sec)

print u'时间戳转为struct_time,但是返回本地时间:\n',time.localtime(time.time())

print u'获取当前时间并且进行格式化:',time.strftime('%y-%m-%d %X',time.localtime())

原文发布于微信公众号 - Python自动化测试(wuya-python)

原文发表时间:2018-04-02

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏desperate633

设计模式之访问者模式(visitor模式)引入访问者模式visitor模式的实例visitor模式分析

Visitor是访问者的意思。 数据结构中保存着元素。一般我们需要对元素进行处理,那么处理元素的代码放在哪里呢?最显然的方法就是放在数据结构的类中,在类中添加...

9530
来自专栏Linyb极客之路

工作流引擎之activiti委托功能实现

异常的意思就是完成任务是要先解决委托,委托任务必须有解决委托这一步骤,当解决委托后,流程并不是进行到下一个节点,而是需要被委托人有完成任务操作时方可进行到下一步...

53730
来自专栏大内老A

通过扩展改善ASP.NET MVC的验证机制[实现篇]

在《使用篇》中我们谈到扩展的验证编程方式,并且演示了本解决方案的三大特性:消息提供机制的分离、多语言的支持和多验证规则的支持,我们现在来看看这样的验证解决方案最...

220100
来自专栏二进制文集

JDK Timer 实现原理分析

注意其中最大的区别,在于 schedule 调用 sched 函数时,将传入的 period 取反了。如果某次执行任务的开始时间延后了,那么此后的每次任务都会延...

10930
来自专栏张善友的专栏

怎么解决web service circular reference 问题

下面是一个非常简单的例子: using System; using System.Data; using System.Configuration; using...

22050
来自专栏林德熙的博客

.net remoting 抛出异常

所有在远程软件运行的类,如果需要传输到本地,都需要继承 MarshalByRefObject 或其他可以序列化的类。

8810
来自专栏陈本布衣

JAXB应用实例

过往的项目中数据存储都离不开数据库,不过最近做的一个项目的某些数据(比如人员信息、菜单、权限等等)却完全没有涉及任何数据库操作,直接XML搞定。这里无意比较优...

42690
来自专栏SpringBoot 核心技术

第三十六章:基于SpringBoot架构重写SpringMVC请求参数装载

30770
来自专栏coolblog.xyz技术专栏

Spring IOC 容器源码分析 - 填充属性到 bean 原始对象

本篇文章,我们来一起了解一下 Spring 是如何将配置文件中的属性值填充到 bean 对象中的。我在前面几篇文章中介绍过 Spring 创建 bean 的流程...

15920
来自专栏黑泽君的专栏

day19_java基础加强_动态代理+注解+类加载器

        Proxy Pattern(即:代理模式),23种常用的面向对象软件的设计模式之一。         代理模式的定义:为其他对象提供一种代理以控...

13740

扫码关注云+社区

领取腾讯云代金券