python 格式化日期

經常使用的時間函數以下python

獲取當前日期:time.time()ide

獲取元組形式的時間戳:time.localtime(time.time())函數

格式化日期的函數(基於元組的形式進行格式化):code

(1)time.asctime(time.localtime(time.time()))orm

(2)time.strftime(format[,t])utf-8

將格式字符串轉換爲時間戳:字符串

time.strptime(str,fmt='%a %b %d %H:%M:%S %Y')get

延遲執行:time.sleep([secs]),單位爲秒it

例1:form

# -*- coding:utf-8 -*-
import time
#當前時間
print time.time()
#時間戳形式

print time.localtime(time.time())
#簡單可讀形式

print time.asctime( time.localtime(time.time()) )
##變成了 Thu May 31 16:32:18 2018

# 格式化成2016-03-20 11:45:39形式
print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 
# 格式化成Sat Mar 28 22:24:24 2016形式
print time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()) 

# 將格式字符串轉換爲時間戳
a = "Sat Mar 28 22:24:24 2016"
print time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y"))

輸出結果

1481036968.19
time.struct_time(tm_year=2016, tm_mon=12, tm_mday=6, tm_hour=23, tm_min=9, tm_sec=28, tm_wday=1, tm_yday=341, tm_isdst=0)
Tue Dec 06 23:09:28 2016
2016-12-06 23:09:28
Tue Dec 06 23:09:28 2016
1459175064.0

例2:某時間與當前比較,若是大於當前時間則調用某個腳本,不然等待半個小時候後繼續判斷

# -*- coding:utf-8 -*-
import time
import sys
import os
#判斷當前時間是否超過某個輸入的時間
def Fuctime(s):
    if time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))>s:
        return True
    else:
        return False

while(1):
    if Fuctime('2016-12-05 00:00:00'):
        #調用某個路徑下的腳本的簡便方法
        os.system("python ./../day_2/Prime.py ./../day_2/inti_prime.txt ./../day_2/res_prime.txt")
        break
    else:
        time.sleep(1800)
        continue

獲取昨天日期

# Filename : test.py
# author by : www.runoob.com

# 引入 datetime 模塊
import datetime
def getYesterday(): 
    today=datetime.date.today() 
    oneday=datetime.timedelta(days=1) 
    yesterday=today-oneday  
    return yesterday

# 輸出
print(getYesterday())
相關文章
相關標籤/搜索