from?https://blog.csdn.net/mighty13/article/details/78147357
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
————————————————
版權聲明:本文為CSDN博主「mighty13」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/mighty13/article/details/78147357
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
