Python 中時間與時間戳轉換

2022-08-20 01:48:11 字數 1842 閱讀 5155

首先,時間戳是指格林威治時間2023年01月01日00時00分00秒(北京時間2023年01月01日08時00分00秒)起至現在的總毫秒數。通俗的講, 時間戳是乙份能夠表示乙份資料在乙個特定時間點已經存在的完整的可驗證的資料。

import time

t =time.time()

print(t) #原始時間資料

print(

int(t)) #秒級時間戳

print(

int(t * 1000

)) #毫秒級時間戳

print(

int(t * 1000000

)) #微秒級時間戳

返回結果

1585806944.976753

1585806944

1585806944976

1585806944976753

import datetime

now = datetime.datetime.now().strftime('

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

now_ms = datetime.datetime.now().strftime('

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

print(now)

print(now_ms)

返回結果

2020-04-02

13:58:51

2020-04-02

13:58:51.294867

dt = '

2020-04-02 13:58:51

'ts = int(time.mktime(time.strptime(dt, "

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

")))

print(ts) 返回

1585807131

ts = 1585807131

dt = time.strftime("

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

", time.localtime(ts))

print(dt) 返回

2020-04-02

13:58:51

dt = '

2020-04-02 13:58:51

'dt_new = datetime.datetime.strptime(dt, '

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

').strftime('

%m/%d/%y %h:%m')

print(dt_new) 返回

04/02/2020

13:58

ta_dt = time.strptime("

2020-04-02 13:58:51

", '

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

ta_ms = time.localtime(1585807131

)print(ta_dt)

print(ta_ms) 返回

time.struct_time(tm_year=2020, tm_mon=4, tm_mday=2, tm_hour=13, tm_min=58, tm_sec=51, tm_wday=3, tm_yday=93, tm_isdst=-1

)time.struct_time(tm_year=2020, tm_mon=4, tm_mday=2, tm_hour=13, tm_min=58, tm_sec=51, tm_wday=3, tm_yday=93, tm_isdst=0)

python 時間 時間戳 轉換

1.簡介 在編寫 時,往往涉及時間 日期 時間戳的相互轉換。python datetime 新增時區 import datetime from dateutil import tz tz sh tz.gettz asia shanghai print datetime.datetime.now tz...

python 時間與時間戳之間的轉換

對於時間資料,如2016 05 05 20 28 54,有時需要與時間戳進行相互的運算,此時就需要對兩種形式進行轉換,在python中,轉換時需要用到time模組,具體的操作有如下的幾種 將如上的時間2016 05 05 20 28 54轉換成時間戳,具體的操作過程為 coding utf 8 im...

python 時間與時間戳之間的轉換

我們通過檔案屬性的獲取,os.stat 方法 import os statinfo os.stat r c 1.txt statinfo 33206,0l,0,0,0,0,29l,1201865413,1201867904,1201865413 使用os.stat的返回值statinfo的三個屬性獲...