Home Backend Development Python Tutorial 详解Python编程中time模块的使用

详解Python编程中time模块的使用

Jun 10, 2016 pm 03:07 PM
python time

一、简介

time模块提供各种操作时间的函数
说明:一般有两种表示时间的方式:
第一种是时间戳的方式(相对于1970.1.1 00:00:00以秒计算的偏移量),时间戳是惟一的
第二种以数组的形式表示即(struct_time),共有九个元素,分别表示,同一个时间戳的struct_time会因为时区不同而不同

  • 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.

夏令时介绍:http://baike.baidu.com/view/100246.htm

UTC介绍:http://wenda.tianya.cn/wenda/thread?tid=283921a9da7c5aef&clk=wttpcts

二、函数介绍

1.asctime()

asctime([tuple]) -> string

将一个struct_time(默认为当时时间),转换成字符串
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.

2.clock()

clock() -> floating point number
该函数有两个功能,
在第一次调用的时候,返回的是程序运行的实际时间;
以第二次之后的调用,返回的是自第一次调用后,到这次调用的时间间隔

注:
在Xinux上使用 time.time() 而在windows中使用time.clock()可以得到更高的精度.
Xinux和Win在实现系统时钟的不同。time.clock()是调用的系统时钟实现,而两个平台又有所不同。
主要问题在于Xinux时钟切换策略:jiffy的实现,因为内核时钟的切换不是连续的而是间隔一段时间(一般而言在1ms~10ms之间)之后才变化, 所以如果是在Xinux中的两次耗时较短的调用,通过time.clock()得到的结果是一样的。

3.sleep(…)

sleep(seconds)
线程推迟指定的时间运行,经过测试,单位为秒
示例:

import time
 if __name__ == '__main__':
   time.sleep(3)
   print "clock1: %s" % time.clock()
   # print "local time: %s" % time.localtime()
   print str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
   time.sleep(3)
   print "clock2: %s" % time.clock()
   # print "local time: %s" % time.localtime()
   print str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
   time.sleep(3)
   print "clock3: %s" % time.clock()
   # print "local time: %s" % time.localtime()
   print str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
Copy after login

结果

clock1: 0.020678
2015-08-09 00:18:31
clock2: 0.020891
2015-08-09 00:18:34
clock3: 0.021068
2015-08-09 00:18:37
Copy after login

4.ctime(…)

ctime(seconds) -> string
将一个时间戳(默认为当前时间)转换成一个时间字符串
例如:

time.ctime()
Copy after login

输出为:

'Sat Mar 28 22:24:24 2009′
Copy after login

5.gmtime(…)

gmtime([seconds]) -> (tm_year, tm_mon, tm_day, tm_hour, tm_min,tm_sec, tm_wday, tm_yday, tm_isdst)
将一个时间戳转换成一个UTC时区(0时区)的struct_time,如果seconds参数未输入,则以当前时间为转换标准

6.localtime(…)

localtime([seconds]) -> (tm_year,tm_mon,tm_day,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst)
将一个时间戳转换成一个当前时区的struct_time,如果seconds参数未输入,则以当前时间为转换标准

7.mktime(…)

mktime(tuple) -> floating point number
将一个以struct_time转换为时间戳

8.strftime(…)

strftime(format[, tuple]) -> string
将指定的struct_time(默认为当前时间),根据指定的格式化字符串输出
python中时间日期格式化符号:

  • %y 两位数的年份表示(00-99)
  • %Y 四位数的年份表示(000-9999)
  • %m 月份(01-12)
  • %d 月内中的一天(0-31)
  • %H 24小时制小时数(0-23)
  • %I 12小时制小时数(01-12)
  • %M 分钟数(00=59)
  • %S 秒(00-59)
  • %a 本地简化星期名称
  • %A 本地完整星期名称
  • %b 本地简化的月份名称
  • %B 本地完整的月份名称
  • %c 本地相应的日期表示和时间表示
  • %j 年内的一天(001-366)
  • %p 本地A.M.或P.M.的等价符
  • %U 一年中的星期数(00-53)星期天为星期的开始
  • %w 星期(0-6),星期天为星期的开始
  • %W 一年中的星期数(00-53)星期一为星期的开始
  • %x 本地相应的日期表示
  • %X 本地相应的时间表示
  • %Z 当前时区的名称
  • %% %号本身
print str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
Copy after login

 2015-08-09 00:18:37
Copy after login

9.strptime(…)

strptime(string, format) -> struct_time
将时间字符串根据指定的格式化符转换成数组形式的时间
例如:
2009-03-20 11:45:39 对应的格式化字符串为:%Y-%m-%d %H:%M:%S
Sat Mar 28 22:24:24 2009 对应的格式化字符串为:%a %b %d %H:%M:%S %Y

10.time(…)

time() -> floating point number
返回当前时间的时间戳(1970纪元后经过的浮点秒数)

三、常用命令

1.python获取当前时间

time.time() 获取当前时间戳
time.localtime() 当前时间的struct_time形式
time.ctime() 当前时间的字符串形式

print time.time()
 print time.localtime()
 print time.ctime()
Copy after login

结果为:

1439051479.08
time.struct_time(tm_year=2015, tm_mon=8, tm_mday=9, tm_hour=0, tm_min=31, tm_sec=19, tm_wday=6, tm_yday=221, tm_isdst=0)
 Sun Aug 9 00:31:19 2015
Copy after login

2.python格式化字符串

格式化成2009-03-20 11:45:39形式

time.strftime(“%Y-%m-%d %H:%M:%S”, time.localtime())
Copy after login

格式化成Sat Mar 28 22:24:24 2009形式

time.strftime(“%a %b %d %H:%M:%S %Y”, time.localtime())
Copy after login

3.将格式字符串转换为时间戳

a = “Sat Mar 28 22:24:24 2009″

b = time.mktime(time.strptime(a,”%a %b %d %H:%M:%S %Y”))
Copy after login

ps:
了解这一块主要是想用time来计算我程序中关键既不的运行时间,所以更多整理这部分内容。至于时间的转化等,后续用得着的时候再来整理。

四、使用time模块计算代码执行效率的精度测试

#python中使用time模块计算代码执行效率 
#测试用time.time()和time.clock()使用精度 
 
import sys 
import time 
import timeit 
default_timer = None 
 
if sys.platform == "win32": 
# On Windows, the best timer is time.clock() 
  default_timer = time.clock 
else: 
# On most other platforms the best timer is time.time() 
  default_timer = time.time 
print default_timer 
timeIn= time.clock() 
for i in range(100): 
  n=i 
timeUse = time.clock()-timeIn 
print timeUse 
 
timeIn = time.time() 
for i in range(100): 
  n=i 
timeUse = time.time()-timeIn 
print timeUse 
 
timeIn = timeit.default_timer() 
for i in range(100): 
  n=i 
timeUse = timeit.default_timer()-timeIn 
print timeUse 
 
  
 
#该段代码在windows下结果如下 
>>>  
4.07873067161e-005 
0.0 
3.5758734839e-005 
 
#因为time.clock() 返回的是处理器时间,而因为 Unix 中 jiffy 的缘故,所以精度不会太高。 
#因此,在Windows 系统中,建议使用 time.clock(),在Unix 系统中,建议使用 time.time(), 
#而使用timeit代替 time,就可以实现跨平台的精度性,使用timeit.default_timer()函数来获取时间 
Copy after login

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

How does PS feathering control the softness of the transition? How does PS feathering control the softness of the transition? Apr 06, 2025 pm 07:33 PM

The key to feather control is to understand its gradual nature. PS itself does not provide the option to directly control the gradient curve, but you can flexibly adjust the radius and gradient softness by multiple feathering, matching masks, and fine selections to achieve a natural transition effect.

How to use mysql after installation How to use mysql after installation Apr 08, 2025 am 11:48 AM

The article introduces the operation of MySQL database. First, you need to install a MySQL client, such as MySQLWorkbench or command line client. 1. Use the mysql-uroot-p command to connect to the server and log in with the root account password; 2. Use CREATEDATABASE to create a database, and USE select a database; 3. Use CREATETABLE to create a table, define fields and data types; 4. Use INSERTINTO to insert data, query data, update data by UPDATE, and delete data by DELETE. Only by mastering these steps, learning to deal with common problems and optimizing database performance can you use MySQL efficiently.

How to set up PS feathering? How to set up PS feathering? Apr 06, 2025 pm 07:36 PM

PS feathering is an image edge blur effect, which is achieved by weighted average of pixels in the edge area. Setting the feather radius can control the degree of blur, and the larger the value, the more blurred it is. Flexible adjustment of the radius can optimize the effect according to images and needs. For example, using a smaller radius to maintain details when processing character photos, and using a larger radius to create a hazy feeling when processing art works. However, it should be noted that too large the radius can easily lose edge details, and too small the effect will not be obvious. The feathering effect is affected by the image resolution and needs to be adjusted according to image understanding and effect grasp.

MySQL download file is damaged and cannot be installed. Repair solution MySQL download file is damaged and cannot be installed. Repair solution Apr 08, 2025 am 11:21 AM

MySQL download file is corrupt, what should I do? Alas, if you download MySQL, you can encounter file corruption. It’s really not easy these days! This article will talk about how to solve this problem so that everyone can avoid detours. After reading it, you can not only repair the damaged MySQL installation package, but also have a deeper understanding of the download and installation process to avoid getting stuck in the future. Let’s first talk about why downloading files is damaged. There are many reasons for this. Network problems are the culprit. Interruption in the download process and instability in the network may lead to file corruption. There is also the problem with the download source itself. The server file itself is broken, and of course it is also broken when you download it. In addition, excessive "passionate" scanning of some antivirus software may also cause file corruption. Diagnostic problem: Determine if the file is really corrupt

Solutions to the service that cannot be started after MySQL installation Solutions to the service that cannot be started after MySQL installation Apr 08, 2025 am 11:18 AM

MySQL refused to start? Don’t panic, let’s check it out! Many friends found that the service could not be started after installing MySQL, and they were so anxious! Don’t worry, this article will take you to deal with it calmly and find out the mastermind behind it! After reading it, you can not only solve this problem, but also improve your understanding of MySQL services and your ideas for troubleshooting problems, and become a more powerful database administrator! The MySQL service failed to start, and there are many reasons, ranging from simple configuration errors to complex system problems. Let’s start with the most common aspects. Basic knowledge: A brief description of the service startup process MySQL service startup. Simply put, the operating system loads MySQL-related files and then starts the MySQL daemon. This involves configuration

MySQL can't be installed after downloading MySQL can't be installed after downloading Apr 08, 2025 am 11:24 AM

The main reasons for MySQL installation failure are: 1. Permission issues, you need to run as an administrator or use the sudo command; 2. Dependencies are missing, and you need to install relevant development packages; 3. Port conflicts, you need to close the program that occupies port 3306 or modify the configuration file; 4. The installation package is corrupt, you need to download and verify the integrity; 5. The environment variable is incorrectly configured, and the environment variables must be correctly configured according to the operating system. Solve these problems and carefully check each step to successfully install MySQL.

How to optimize database performance after mysql installation How to optimize database performance after mysql installation Apr 08, 2025 am 11:36 AM

MySQL performance optimization needs to start from three aspects: installation configuration, indexing and query optimization, monitoring and tuning. 1. After installation, you need to adjust the my.cnf file according to the server configuration, such as the innodb_buffer_pool_size parameter, and close query_cache_size; 2. Create a suitable index to avoid excessive indexes, and optimize query statements, such as using the EXPLAIN command to analyze the execution plan; 3. Use MySQL's own monitoring tool (SHOWPROCESSLIST, SHOWSTATUS) to monitor the database health, and regularly back up and organize the database. Only by continuously optimizing these steps can the performance of MySQL database be improved.

See all articles