python時間函式和常用格式化

2021-09-01 07:33:18 字數 3993 閱讀 4370

使用之前import:

import time,datetime

下面的函式在python2.7裡可以正常執行,但python2.4可能不支援某些方法。比如python2.4.3中報錯:

attributeerror: type object 'datetime.datetime' has no attribute 'strptime'

格式化當前時間則為:

首選:time.strftime('%y-%m-%d %h:%m:%s')

其次:datetime.datetime.strftime(datetime.d atetime.now(), '%y-%m-%d %h:%m:%s')

最後:str(datetime.datetime.now())[:19]

獲取日期差:

oneday = datetime.timedelta(days=1)

today = datetime.date.today()

yesterday  = datetime.date.today() - oneday

tomorrow = datetime.date.today() + oneday

today_zero_time = datetime.datetime.strftime(today, '%y-%m-%d %h:%m:%s')

print today_zero_time

2013-05-21 00:00:00

獲取時間差:

oneday = datetime.timedelta(days=1)

today_time = datetime.datetime.now()

yesterday_time = datetime.datetime.now() - oneday

tomorrow_time  = datetime.datetime.now() + oneday

注意時間是浮點數,帶毫秒。如下:

print tomorrow_time

2013-05-22 10:34:43.873844

那麼要獲取當前時間,需要格式化一下:

oneday = datetime.timedelta(days=1)

today_time = datetime.datetime.now()

yesterday_time = datetime.datetime.now() - oneday

tomorrow_time  = datetime.datetime.now() + oneday

tomorrow_time = datetime.datetime.strftime(today_time, '%y-%m-%d %h:%m:%s')

執行結果如下所示:

print tomorrow_time

2013-05-21 10:34:43

獲取上個月最後一天:

last_month_last_day = datetime.date(datetime.date.today().year,datetime.date.today().month,1)-datetime.timedelta(1) 

字串格式轉秒數:

expire_time = "2013-05-21 09:50:35"

d = datetime.datetime.strptime(expire_time,"%y-%m-%d %h:%m:%s")

time_sec_float = time.mktime(d.timetuple())

print time_sec_float

1369101035.0

注意python裡獲取到的是float型別的秒數,而不是整形。如果要獲得整數,可以用int(time_sec_float)

秒數轉字串:

time_sec = time.time()

time.strftime("%y-%m-%d %h:%m:%s", time.localtime(time_sec))

python的時間轉換函式搞得太抽象複雜,因此我包裝了乙個函式,傳入字串可以獲取到時間的各種格式,傳入秒數可以獲取字串格式時間(這個是很簡單的),還傳入兩個字串格式的時間,以計算他們的時間差。

#coding=gbk

import time, datetime

# 傳入乙個字串格式的時間2013-05-21 14:31:23,可以得到各種格式的時間

class timeformat:

def __init__(self, time_string="1970-1-1 00:00:00"):

self.time_string = self._format_time_string(time_string)

def _format_time_string(self, time_string):

return time.strftime("%y-%m-%d %h:%m:%s", self.get_struct(time_string))

@property

def time_struct(self):

return self.get_struct(self.time_string)

def get_struct(self, time_string):

return time.localtime(self.get_seconds(time_string))

@property

def seconds(self):

return self.get_seconds(self.time_string)

def get_seconds(self, time_string):

d = datetime.datetime.strptime(time_string, "%y-%m-%d %h:%m:%s")

return time.mktime(d.timetuple())

def get_string(self, time_sec):

return time.strftime("%y-%m-%d %h:%m:%s", time.localtime(time_sec))

# 對於中國的時間,是1970-01-01 08:00:00

def check_diff_time(self, t1, t2):

sec1 = int(self.get_seconds(t1))

sec2 = int(self.get_seconds(t2))

if sec1 > sec2:

secdiff = sec1 - sec2

else:

secdiff = sec2 - sec1

d = self.get_struct(self.get_string(secdiff))

day = d.tm_mday

hour = d.tm_hour

if d.tm_hour < 8:

day -= 1

hour = 24 + (d.tm_hour - 8)

else:

hour = d.tm_hour - 8

return

if __name__ == "__main__":

t1 = timeformat("2015-04-01 12:23:23")

t2 = timeformat("2014-03-10 22:23:23")

print t1.seconds

print t2.seconds

d = t1.check_diff_time(t1.time_string, t2.time_string)

print "%s 和 %s 時間差為:%s年%s月%s天%s小時%s分%s秒" %(t1.time_string, t2.time_string, d["year"], d["month"], d["day"], d["hour"], d["min"], d["sec"])

python之常用的時間格式轉換

記得匯入需要的包例如 import datetime import time1.utc時間轉化為當地時間 cst時間 def utc2local utc date now stamp time.time local time datetime.datetime.fromtimestamp now s...

Python時間格式

關於python時間格式總結 1 時間戳 import time print time.time 直接輸出時間戳 1481357223 利用time時間模組轉換,格式化時間戳為本地的時間 time.localtime time.time time.struct time tm year 2016,t...

python時間格式

1.日期輸出格式化 datetime string import datetime now datetime.datetime.now now.strftime y m d h m s 輸出 2015 04 07 19 11 21 strftime是datetime類的例項方法。2.日期輸出格式化 ...