简单学习Python time模块

yipeiwu_com6年前Python基础

本文针对Python time模块进行分类学习,希望对大家的学习有所帮助。

一.壁挂钟时间

1.time()

time模块的核心函数time(),它返回纪元开始的秒数,返回值为浮点数,具体精度依赖于平台。

>>>import time

>>>time.time()

1460599046.85416

2.ctime()

浮点数一般用于存储和比较日期,但是对人类不友好,要记录和打印时间,可以使用ctime()。

>>>import time

>>>time.ctime()

'Thu Apr 14 10:03:58 2016'

>>> later = time.time()+5

>>> time.ctime(later)

'Thu Apr 14 10:05:57 2016'

二.处理器时钟时间

clock()返回处理器时钟时间,它的返回值一般用于性能测试与基准测试。因此它们反映了程序的实际运行时间。

>>>import time

>>>time.clock()

0.07

三.时间组成

time模块定义了struct_time来维护时间和日期,其中分开存储各个组成部分,以便访问。

import time

def show_struct(s):

   print 'tm_year:", s.tm_year

   print 'tm_mon:", s.tm_mon

   print "tm_mday:", s.tm_mday

   print "tm_hour:",s.tm_hour

   print "tm_min:", s.tm_min

   print "tm_sec:", s.tm_sec

   print "tm_wday:", s.tm_wday

   print "tm_yday:", s.tm_yday

show_struct(time.gmtime())

show_struct(time.localtime())

gmtime()用于获取UTC时间,localtime()用于获取当前时区的当前时间,UTC时间实际就是格林尼治时间,它与中国时间的时差为八个小时。

locatime() = gmtime() + 8hour

四.处理时区

1.获取时间差

>>>import time

>>>time.timezone/3600

-8

2.设置时区

ZONES = ["GMT", "EUROPE/Amsterdam']

for zone in ZONES:

   os.environ["TZ"] = zone

   time.tzset()

五.解析和格式化时间

time模块提供了两个函数strptime()和strftime(),可以在struct_time和时间值字符串之间转换。

1.strptime()

用于将字符串时间转换成struct_time格式:

>>> now=time.ctime()

>>> time.strptime(now)

time.struct_time(tm_year=2016, tm_mon=4, tm_mday=14, tm_hour=10, tm_min=48, tm_sec=40, tm_wday=3, tm_yday=105, tm_isdst=-1)

 

2.strftime()

用于时间的格式化输出

>>> from time import gmtime, strftime

>>> strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())

'Thu, 28 Jun 2001 14:17:15 +0000'

3.mktime()

用于将struct_time转换成时间的浮点数表示

>>>from time import mktime, gmtime

>>>mktime(gmtime())

1460573789.0

六.sleep()

sleep函数用于将当前线程交出,要求它等待系统将其再次唤醒,如果写程序只有一个线程,这实际上就会阻塞进程,什么也不做。

import time

def fucn():

   time.sleep(5)

   print "hello, world"

执行上面的代码,将等待5秒钟之后再输出信息。

以上就是本文的全部内容,希望大家可以对Python time模块有个大概的了解。

相关文章

python线程中的同步问题及解决方法

多线程开发可能遇到的问题 假设两个线程t1和t2都要对num=0进行增1运算,t1和t2都各对num修改1000000次,num的最终的结果应该为2000000。但是由于是多线程访问,有...

python中redis查看剩余过期时间及用正则通配符批量删除key的方法

具体代码如下所示: # -*- coding: utf-8 -*- import redis import datetime ''' # 1. redis设置过期时间的两种方式 e...

使用 tf.nn.dynamic_rnn 展开时间维度方式

使用 tf.nn.dynamic_rnn 展开时间维度方式

对于单个的 RNNCell , 使用色的 call 函数进行运算时 ,只是在序列时间上前进了一步 。如使用 x1、 ho 得到此h1, 通过 x2 、 h1 得到 h2 ...

Python数学形态学实例分析

Python数学形态学实例分析

本文实例讲述了Python数学形态学。分享给大家供大家参考,具体如下: 一 原始随机图像 1、代码 import numpy as np import matplotlib.pypl...

python对验证码降噪的实现示例代码

python对验证码降噪的实现示例代码

前言: 最近写爬虫会经常遇到一些验证码识别的问题,现如今的验证码已经是五花八门,刚开始的验证码就是简单的对生成的验证码图片进行一些干扰,但是随着计算机视觉库的 发展壮大,可以轻松解决简单...