Python之time模塊的時間戳,時間字符串格式化與轉(zhuǎn)換方法(13位時間戳)
Python處理時間和時間戳的內(nèi)置模塊就有time,和datetime兩個,本文先說time模塊。
關(guān)于時間戳的幾個概念
時間戳,根據(jù)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模塊與時間戳和時間相關(guān)的重要函數(shù)
time.time() 生成當(dāng)前的時間戳,格式為10位整數(shù)的浮點數(shù)。
time.strftime()根據(jù)時間元組生成時間格式化字符串。
time.strptime()根據(jù)時間格式化字符串生成時間元組。time.strptime()與time.strftime()為互操作。
time.localtime()根據(jù)時間戳生成當(dāng)前時區(qū)的時間元組。
time.mktime()根據(jù)時間元組生成時間戳。
示例
關(guān)于時間戳和格式化字符串的簡單示例如下
import time #生成當(dāng)前時間的時間戳,只有一個參數(shù)即時間戳的位數(shù),默認為10位,輸入位數(shù)即生成相應(yīng)位數(shù)的時間戳,比如可以生成常用的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 #將時間戳規(guī)范為10位時間戳 def timestamp_to_timestamp10(time_stamp): time_stamp = int (time_stamp* (10 ** (10-len(str(time_stamp))))) return time_stamp #將當(dāng)前時間轉(zhuǎn)換為時間字符串,默認為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位時間戳轉(zhuǎn)換為時間字符串,默認為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 #將時間字符串轉(zhuǎn)換為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 #不同時間格式字符串的轉(zhuǎn)換 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'))
結(jié)果為
1506836224000 2017-10-01 13:37:04 2017-10-01 08:09:32 1506816572 1506816572 2017-10-01 08-09-32
以上這篇Python之time模塊的時間戳,時間字符串格式化與轉(zhuǎn)換方法(13位時間戳)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
- python datetime 和時間戳互相轉(zhuǎn)換問題
- python中時間轉(zhuǎn)換datetime和pd.to_datetime詳析
- Python datetime和unix時間戳之間相互轉(zhuǎn)換的講解
- Python中時間datetime的處理與轉(zhuǎn)換用法總結(jié)
- python utc datetime轉(zhuǎn)換為時間戳的方法
- python sys,os,time模塊的使用(包括時間格式的各種轉(zhuǎn)換)
- Python中實現(xiàn)對Timestamp和Datetime及UTC時間之間的轉(zhuǎn)換
- python 時間的訪問和轉(zhuǎn)換 time示例小結(jié)
相關(guān)文章
報錯No?module?named?numpy問題的解決辦法
之前安裝了Python,后來因為練習(xí)使用Python寫科學(xué)計算的東西,又安裝了Anaconda,但是安裝Anaconda之后又出現(xiàn)了一個問題,下面這篇文章主要給大家介紹了關(guān)于報錯No?module?named?numpy問題的解決辦法,需要的朋友可以參考下2022-08-08