搜尋
首頁後端開發Python教學详解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()))

结果

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

4.ctime(…)

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

time.ctime()

输出为:

'Sat Mar 28 22:24:24 2009′

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()))
 2015-08-09 00:18:37

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

结果为:

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

2.python格式化字符串

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

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

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

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

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

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

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

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()函数来获取时间 

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python的科學計算中如何使用陣列?Python的科學計算中如何使用陣列?Apr 25, 2025 am 12:28 AM

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

您如何處理同一系統上的不同Python版本?您如何處理同一系統上的不同Python版本?Apr 25, 2025 am 12:24 AM

你可以通過使用pyenv、venv和Anaconda來管理不同的Python版本。 1)使用pyenv管理多個Python版本:安裝pyenv,設置全局和本地版本。 2)使用venv創建虛擬環境以隔離項目依賴。 3)使用Anaconda管理數據科學項目中的Python版本。 4)保留系統Python用於系統級任務。通過這些工具和策略,你可以有效地管理不同版本的Python,確保項目順利運行。

與標準Python陣列相比,使用Numpy數組的一些優點是什麼?與標準Python陣列相比,使用Numpy數組的一些優點是什麼?Apr 25, 2025 am 12:21 AM

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基於基於duetoc的iMplation,2)2)他們的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函數函數函數函數構成和穩定性構成和穩定性的操作,製造

陣列的同質性質如何影響性能?陣列的同質性質如何影響性能?Apr 25, 2025 am 12:13 AM

數組的同質性對性能的影響是雙重的:1)同質性允許編譯器優化內存訪問,提高性能;2)但限制了類型多樣性,可能導致效率低下。總之,選擇合適的數據結構至關重要。

編寫可執行python腳本的最佳實踐是什麼?編寫可執行python腳本的最佳實踐是什麼?Apr 25, 2025 am 12:11 AM

到CraftCraftExecutablePythcripts,lollow TheSebestPractices:1)Addashebangline(#!/usr/usr/bin/envpython3)tomakethescriptexecutable.2)setpermissionswithchmodwithchmod xyour_script.3)

Numpy數組與使用數組模塊創建的數組有何不同?Numpy數組與使用數組模塊創建的數組有何不同?Apr 24, 2025 pm 03:53 PM

numpyArraysareAreBetterFornumericalialoperations andmulti-demensionaldata,而learthearrayModuleSutableforbasic,內存效率段

Numpy數組的使用與使用Python中的數組模塊陣列相比如何?Numpy數組的使用與使用Python中的數組模塊陣列相比如何?Apr 24, 2025 pm 03:49 PM

numpyArraySareAreBetterForHeAvyNumericalComputing,而lelethearRayModulesiutable-usemoblemory-connerage-inderabledsswithSimpleDatateTypes.1)NumpyArsofferVerverVerverVerverVersAtility andPerformanceForlargedForlargedAtatasetSetsAtsAndAtasEndCompleXoper.2)

CTYPES模塊與Python中的數組有何關係?CTYPES模塊與Python中的數組有何關係?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingingangandmanipulatingc-stylarraysinpython.1)usectypestoInterfacewithClibrariesForperfermance.2)createc-stylec-stylec-stylarraysfornumericalcomputations.3)passarraystocfunctions foreforfunctionsforeffortions.however.however,However,HoweverofiousofmemoryManageManiverage,Pressiveo,Pressivero

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器