python time模組型別轉換

2021-10-13 06:07:10 字數 1363 閱讀 7589

所在模組, time.py

主要在三個型別之間轉換

s: 指秒數

tuple:(即時間struct)

str: 時間串

很明顯, tuple起到乙個中間結構作用, 連線了s, str.

1。s, tuple 相互轉換

i. s轉tuple

time.localtime([s]) s--> tuple, 當沒有引數時,預設為當前時間.

time.gmtime(s) s->tuple 差異如下

>>> import time

>>> time.localtime(0)

time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=8, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)

>>> time.gmtime(0)

time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)

gmtime為格林威治時間,localtime為北京時間,北京時間=格林尼治時間+8小時。

同時可以看出,s是以2023年1月1日零時計算過去的秒數.

ii. tuple->s

time.mktime(tuple) tuple-->s:float

2。 tuple, str轉換

time.strftime(format, tuple) tuple->str

time.strptime(str, format) str->tuple

>>> import time

>>> a = time.localtime()

>>> type(a)

>>> time.strftime('%y-%m-%d',a)

'2020-12-28'

>>> time.strftime('%y-%m-%d %h:%m:%s',a)

'2020-12-28 11:55:43'

>>> b = time.strftime('%y-%m-%d %h:%m:%s',a)

>>> type(b)

>>> time.strptime(b,'%y-%m-%d %h:%m:%s')

time.struct_time(tm_year=2020, tm_mon=12, tm_mday=28, tm_hour=11, tm_min=55, tm_sec=43, tm_wday=0, tm_yday=363, tm_isdst=-1)

Python time模組操作

參考 python 程式能用很多方式處理日期和時間,轉換日期格式是乙個常見的功能。python 提供了乙個 time 和 calendar 模組可以用於格式化日期和時間。時間間隔是以秒為單位的浮點小數。每個時間戳都以自從1970年1月1日午夜 曆元 經過了多長時間來表示。python 的 time ...

Python time模組總結

工作中總能用到time,datetime模組,多數時候用於時間日期不同格式間的轉換。如果沒有熟練掌握各函式用法,那麼將不能快速解決問題。今天詳細整理一下time模組的用法,有不當之處還請指正。先上總結 import time time.time 返回當前時間戳 time.mktime tupleti...

python time模組詳解

time模組中時間表現的格式主要有三種 a timestamp時間戳,時間戳表示的是從1970年1月1日00 00 00開始按秒計算的偏移量 b struct time時間元組,共有九個元素組。c format time 格式化時間,已格式化的結構使時間更具可讀性。包括自定義格式和固定格式。1 時間...