Python之time模組的時間戳、時間字串格式化與轉換(13位時間戳)
阿新 • • 發佈:2019-01-04
Python處理時間和時間戳的內建模組就有time
,和datetime
兩個,本文先說time
模組。
關於時間戳的幾個概念
- 時間戳,根據1970年1月1日00:00:00開始按秒計算的偏移量。
- 時間元組(
struct_time
),包含9個元素。
time.struct_time(tm_year=2017, tm_mon=10, tm_mday=1, tm_hour=14, tm_min=21, tm_sec=57, tm_wday=6, tm_yday=274, tm_isdst=0)
- 時間格式字串,字串形式的時間。
time
模組與時間戳和時間相關的重要函式
time.time()
生成當前的時間戳,格式為10位整數的浮點數。time.strftime()
根據時間元組生成時間格式化字串。time.strptime()
根據時間格式化字串生成時間元組。time.strptime()
與time.strftime()
為互操作。time.localtime()
根據時間戳生成當前時區的時間元組。time.mktime()
根據時間元組生成時間戳。
示例
關於時間戳和格式化字串的簡單示例如下
import time
#生成當前時間的時間戳,只有一個引數即時間戳的位數,預設為10位,輸入位數即生成相應位數的時間戳,比如可以生成常用的13位時間戳
def now_to_timestamp(digits = 10) :
time_stamp = time.time()
digits = 10 ** (digits -10)
time_stamp = int(round(time_stamp*digits))
return time_stamp
#將時間戳規範為10位時間戳
def timestamp_to_timestamp10(time_stamp):
time_stamp = int (time_stamp* (10 ** (10-len(str(time_stamp)))))
return time_stamp
#將當前時間轉換為時間字串,預設為2017-10-01 13:37:04格式
def now_to_date(format_string="%Y-%m-%d %H:%M:%S"):
time_stamp = int(time.time())
time_array = time.localtime(time_stamp)
str_date = time.strftime(format_string, time_array)
return str_date
#將10位時間戳轉換為時間字串,預設為2017-10-01 13:37:04格式
def timestamp_to_date(time_stamp, format_string="%Y-%m-%d %H:%M:%S"):
time_array = time.localtime(time_stamp)
str_date = time.strftime(format_string, time_array)
return str_date
#將時間字串轉換為10位時間戳,時間字串預設為2017-10-01 13:37:04格式
def date_to_timestamp(date, format_string="%Y-%m-%d %H:%M:%S"):
time_array = time.strptime(date, format_string)
time_stamp = int(time.mktime(time_array))
return time_stamp
#不同時間格式字串的轉換
def date_style_transfomation(date, format_string1="%Y-%m-%d %H:%M:%S",format_string2="%Y-%m-%d %H-%M-%S"):
time_array = time.strptime(date, format_string1)
str_date = time.strftime(format_string2, time_array)
return str_date
實驗
print(now_to_date())
print(timestamp_to_date(1506816572))
print(date_to_timestamp('2017-10-01 08:09:32'))
print(timestamp_to_timestamp10(1506816572546))
print(date_style_transfomation('2017-10-01 08:09:32'))
結果為
1506836224000
2017-10-01 13:37:04
2017-10-01 08:09:32
1506816572
1506816572
2017-10-01 08-09-32