python3獲取時間戳 秒數和日期時間的相互轉換

2021-09-12 02:27:10 字數 1805 閱讀 3582

**如下:

import time

import datetime

t = time.time(

)print

(t)#原始時間資料

print

(int

(t))

#秒級時間戳

print

(int

(round

(t *

1000))

)#毫秒級時間戳

nowtime =

lambda

:int

(round

(t *

1000))

print

(nowtime())

;#毫秒級時間戳,基於lambda

print

(datetime.datetime.now(

).strftime(

'%y-%m-%d %h:%m:%s'))

#日期格式化

結果:

1552267863.7501628

1552267863

1552267863750

1552267863750

2019-03-11 09:31:03

時間格式說明:

方法**:

import time

defgettime

(seconds)

: timearray = time.localtime(seconds)

otherstyletime = time.strftime(

"%h:%m:%s"

, timearray)

print

(otherstyletime)

if __name__ ==

'__main__'

: time = gettime(

1551863258

)print

(time)

結果:

17:07:38

process finished with exit code 0

上面例子中的%h:%m:%s可以根據需要設定為別的格式,如%y_%m_%d %h:%m:%s

示例**:

import time

import datetime

defcomposetime

(time1)

: time2 = datetime.datetime.strptime(time1,

"%y_%m_%d %h:%m:%s"

) time3 = time.mktime(time2.timetuple())

time4 =

int(time3)

return time4

if __name__ ==

'__main__'

: time = composetime(

"2019_03_06 17:07:38"

)print

(time)

結果:

1551863258

process finished with exit code 0

說明:上面**中之所以加了個int(time3)是因為time3的值其實是1551863258.0,故以此方法來去掉後邊的小數點;

python3 獲取兩個時間戳相差多少天

code import time import datetime t datetime.datetime.now 當前日期 t1 t.strftime y m d h m s 轉為秒級時間戳 ts1 time.mktime time.strptime t1,y m d h m s 轉為毫秒級 end...

Android 獲取時間戳 和時間戳轉日期

獲取系統時間戳 public string gettime 獲取系統時間 long currenttime system.currenttimemillis dateformat formatter new dateformat yyyy年 mm月dd日 hh時mm分ss秒 date date ne...

Golang獲取時間戳和時間操作

time.now unix 時間戳 秒 time.now unixnano 時間戳 納秒 time.now unixnano 1e6 時間戳 毫秒 time.now unixnano 1e9 時間戳 納秒轉換為秒 注 1秒 1000毫秒 1毫秒 1000微秒 1微秒 1000納秒 1e6是指數表達形...