Python time strptime()方法 时间操作
描述
Python time strptime() 函數(shù)根據(jù)指定的格式把一個(gè)時(shí)間字符串解析為時(shí)間元組。
語(yǔ)法
strptime()方法語(yǔ)法:
time.strptime(string[, format])參數(shù)
- string -- 時(shí)間字符串。
- format -- 格式化字符串。
返回值
返回struct_time對(duì)象。
說(shuō)明
python中時(shí)間日期格式化符號(hào):
- %y 兩位數(shù)的年份表示(00-99)
- %Y 四位數(shù)的年份表示(000-9999)
- %m 月份(01-12)
- %d 月內(nèi)中的一天(0-31)
- %H 24小時(shí)制小時(shí)數(shù)(0-23)
- %I 12小時(shí)制小時(shí)數(shù)(01-12)
- %M 分鐘數(shù)(00=59)
- %S 秒(00-59)
- %a 本地簡(jiǎn)化星期名稱
- %A 本地完整星期名稱
- %b 本地簡(jiǎn)化的月份名稱
- %B 本地完整的月份名稱
- %c 本地相應(yīng)的日期表示和時(shí)間表示
- %j 年內(nèi)的一天(001-366)
- %p 本地A.M.或P.M.的等價(jià)符
- %U 一年中的星期數(shù)(00-53)星期天為星期的開(kāi)始
- %w 星期(0-6),星期天為星期的開(kāi)始
- %W 一年中的星期數(shù)(00-53)星期一為星期的開(kāi)始
- %x 本地相應(yīng)的日期表示
- %X 本地相應(yīng)的時(shí)間表示
- %Z 當(dāng)前時(shí)區(qū)的名稱
- %% %號(hào)本身
實(shí)例
以下實(shí)例展示了 strptime() 函數(shù)的使用方法:
實(shí)例(Python 2.0+) #!/usr/bin/python # -*- coding: UTF-8 -*-import timestruct_time = time.strptime("30 Nov 00", "%d %b %y") print "返回的元組: %s " % struct_time以上實(shí)例輸出結(jié)果為:
返回的元組: time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)?
?
Python time mktime()方法
描述
Python time mktime() 函數(shù)執(zhí)行與gmtime(), localtime()相反的操作,它接收struct_time對(duì)象作為參數(shù),返回用秒數(shù)來(lái)表示時(shí)間的浮點(diǎn)數(shù)。
如果輸入的值不是一個(gè)合法的時(shí)間,將觸發(fā) OverflowError 或 ValueError。
語(yǔ)法
mktime()方法語(yǔ)法:
time.mktime(t)參數(shù)
- t -- 結(jié)構(gòu)化的時(shí)間或者完整的9位元組元素。
返回值
返回用秒數(shù)來(lái)表示時(shí)間的浮點(diǎn)數(shù)。
實(shí)例
以下實(shí)例展示了 mktime() 函數(shù)的使用方法:
#!/usr/bin/python import timet = (2009, 2, 17, 17, 3, 38, 1, 48, 0) secs = time.mktime( t ) print "time.mktime(t) : %f" % secs print "asctime(localtime(secs)): %s" % time.asctime(time.localtime(secs))以上實(shí)例輸出結(jié)果為:
time.mktime(t) : 1234915418.000000 asctime(localtime(secs)): Tue Feb 17 17:03:38 2009?
os.path.getmtime(path)
這是一個(gè)Unix時(shí)間戳。可以使用datetime庫(kù)來(lái)處理時(shí)間戳:
import datetime, os t = os.path.getmtime('/') tt = datetime.datetime.fromtimestamp(t) ttt = tt.strftime('%Y') # 這是個(gè)時(shí)間格式化字符串,只能返回年份。更多使用方法參見(jiàn)手冊(cè)。 print (ttt)?
?
1、獲取當(dāng)前日期時(shí)間:
import time print (time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))?
2、獲取當(dāng)天日期:
import datetime print(datetime.date.today())?
3、將當(dāng)天時(shí)間日期轉(zhuǎn)化為數(shù)字
import datetime print("".join(str(datetime.date.today().replace(day=1)).split("-")))?
轉(zhuǎn)載于:https://www.cnblogs.com/lmh001/p/9997563.html
總結(jié)
以上是生活随笔為你收集整理的Python time strptime()方法 时间操作的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: tomcat配置一个线程来调试Threa
- 下一篇: NUC970开发资源