这篇文章主要介绍了Python计时相关操作,涉及time,datetime模块的使用技巧,包括时间戳、时间差、日期格式等操作方法,需要的朋友可以参考下
本文实例讲述了Python计时相关操作。分享给大家供大家参考,具体如下:
内容目录:
1. 时间戳
2. 当前时间
3. 时间差
4. python中时间日期格式化符号
5. 例子
一、时间戳
时间戳是自 1970 年 1 月 1 日(08:00:00 GMT)至当前时间的总秒数。它也被称为 Unix 时间戳(Unix Timestamp),它在unix、c的世界里随处可见;常见形态是浮点数,小数点后面是毫秒。两个时间戳相减就是时间间隔(单位:秒)。
例:
import time time1 = time.time() time.sleep(15) time2 = time.time() print time2 - time1
其中,time.sleep()是休眠函数,单位:秒。
二、当前时间
>>> import datetime,time >>> now = time.strftime("%Y-%m-%d %H:%M:%S") >>> print now 2016-04-30 17:02:26 >>> now = datetime.datetime.now() >>> print now
三、时间差
#1 昨天00:00到昨天23:59
>>> import datetime >>> yestoday = datetime.datetime.now() - datetime.timedelta(days=1) >>> t1 = "%s-00-00-00" % yestoday.strftime("%Y-%m-%d") >>> t2 = "%s-23-59-59" % yestoday.strftime("%Y-%m-%d") >>> print 't1', t1 t1 2016-04-29-00-00-00 >>> print 't2', t2 t2 2016-04-29-23-59-59
#2 现在往后10小时
>>> d1 = datetime.datetime.now() >>> d3 = d1 + datetime.timedelta(hours=10) >>> d3.ctime() 'Sun May 1 03:09:58 2
#3 这么一会的秒数、微妙数(注意是取秒、微妙部分,并不是等价转换)
>>> import datetime >>> starttime = datetime.datetime.now() >>> endtime = datetime.datetime.now() >>> starttime = datetime.datetime.now() >>> endtime = datetime.datetime.now() >>> print endtime - starttime 0:00:07.390988 >>> print (endtime - starttime).seconds 7 >>> print (endtime - starttime).microseconds 390988
文件的时间戳
>>> import os >>> statinfo=os.stat(r"C:/1.txt") >>> statinfo (33206, 0L, 0, 0, 0, 0, 29L, 1201865413, 1201867904, 1201865413)
注:使用os.stat的返回值statinfo中的后三项是文件的st_atime (访问时间), st_mtime (修改时间), st_ctime(创建时间),例如,取得文件修改时间:
>>> statinfo.st_mtime 1201865413.8952832
注:这个时间是一个linux时间戳,可以转换成易于理解的格式:
>>> import time >>> time.localtime(statinfo.st_ctime) (2008, 2, 1, 19, 30, 13, 4, 32, 0)
注:2008年2月1日的19时30分13秒(2008-2-1 19:30:13)
四、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 当前时区的名称
%% %号本身
五、例子
#! coding:utf-8 ''''' 日期相关的操作 ''' from datetime import datetime from datetime import timedelta import calendar DATE_FMT = '%Y-%m-%d' DATETIME_FMT = '%Y-%m-%d %H:%M:%S' DATE_US_FMT = '%d/%m/%Y' ''''' 格式化常用的几个参数 Y : 1999 y :99 m : mouth 02 12 M : minute 00-59 S : second d : day H : hour ''' def dateToStr(date): '''''把datetime类型的时间格式化自己想要的格式''' return datetime.strftime(date, DATETIME_FMT) def strToDate(strdate): '''''把str变成日期用来做一些操作''' return datetime.strptime(strdate, DATETIME_FMT) def timeElement(): '''''获取一个时间对象的各个元素''' now = datetime.today() print 'year: %s month: %s day: %s' %(now.year, now.month, now.day) print 'hour: %s minute: %s second: %s' %(now.hour, now.minute, now.second) print 'weekday: %s ' %(now.weekday()+1) #一周是从0开始的 def timeAdd(): ''''' 时间的加减,前一天后一天等操作 datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]]) 参数可以是正数也可以是负数 得到的对象可以加也可以减 乘以数字和求绝对值 ''' atime = timedelta(days=-1) now = datetime.strptime('2001-01-30 11:01:02', DATETIME_FMT) print now + atime print now - abs(atime) print now - abs(atime)*31 def lastFirday(): today = datetime.today() targetDay = calendar.FRIDAY thisDay = today.weekday() de = (thisDay - targetDay) % 7 res = today - timedelta(days=de) print res def test(): print dateToStr(datetime.today()) print strToDate('2013-01-31 12:00:01') timeElement() timeAdd() lastFirday() if name=='main': test()
结果
Connected to pydev debugger (build 141.1899) 2016-05-18 10:40:26 2013-01-31 12:00:01 year: 2016 month: 5 day: 18 hour: 10 minute: 41 second: 13 weekday: 3 2001-01-29 11:01:02 2001-01-29 11:01:02 2000-12-30 11:01:02 2016-05-13 10:41:37.001000
以上是Python计时相关操作的详细介绍的详细内容。更多信息请关注PHP中文网其他相关文章!

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

你可以通过使用pyenv、venv和Anaconda来管理不同的Python版本。1)使用pyenv管理多个Python版本:安装pyenv,设置全局和本地版本。2)使用venv创建虚拟环境以隔离项目依赖。3)使用Anaconda管理数据科学项目中的Python版本。4)保留系统Python用于系统级任务。通过这些工具和策略,你可以有效地管理不同版本的Python,确保项目顺利运行。

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基于基于duetoc的iMplation,2)2)他们的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函数函数函数函数构成和稳定性构成和稳定性的操作,制造

数组的同质性对性能的影响是双重的:1)同质性允许编译器优化内存访问,提高性能;2)但限制了类型多样性,可能导致效率低下。总之,选择合适的数据结构至关重要。

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

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

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

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


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

Atom编辑器mac版下载
最流行的的开源编辑器

禅工作室 13.0.1
功能强大的PHP集成开发环境