打印當前時間戳
import time import datetime t = time.time() print (t) #原始時間數據 print (int(t)) #秒級時間戳 print (int(round(t * 1000))) #毫秒級時間戳 print (int(round(t * 1000000))) #微秒級時間戳
將當前時間轉換成字符串
import datetime now_str = datetime.strftime(datetime.now(), "%Y%m%d%H%M%S%f") #%f表示精確到微秒
python 時間戳轉為字符串
方法一
import datetime import time stamp = int(time.time()) print datetime.datetime.fromtimestamp(stamp) 2017-07-29 16:08:32
方法二
>>> time.strftime("%Y-%m-%d %H:%M", time.localtime(stamp)) '2017-07-29 16:08' >>>
timedalte()
timedalte 是datetime中的一個對象,該對象表示兩個時間的差值
構造函數:datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
其中參數都是可選,默認值為0,如果只有一個參數,則表示天數
獲取當前時間整點值
now_datetime = datetime.datetime.now() # 當前時間,格式為datetime類型 # 把當前時間去除分、秒和毫秒后即是小時級別的整點值了 now_datetime_hour = now_datetime + datetime.timedelta(minutes=-now_datetime.minute, seconds=-now_datetime.second, microseconds=-now_datetime.microsecond)
打印結果:
now_datetime ======> 2021-12-19 16:15:47.156853
now_datetime_hour ======> 2021-12-19 16:00:00
將時間字符串轉換為時間戳
time.strptime(t, format)函數可以將 時間字符串t按照 format格式解析后轉成換一個下面這樣的時間結構體struct_time,
time.struct_time(tm_year=2021, tm_mon=11, tm_mday=20, tm_hour=14, tm_min=54, tm_sec=36, tm_wday=5, tm_yday=324, tm_isdst=-1)
time.mktime(t) 接受一個上面的時間結構體參數,返回一個帶有一位小數的毫秒級時間戳
example1:
t = time.strptime('2021-11-20 14:54:36', "%Y-%m-%d %H:%M:%S") print(t) #time.struct_time(tm_year=2021, tm_mon=11, tm_mday=20, tm_hour=14, tm_min=54, tm_sec=36, tm_wday=5, tm_yday=324, tm_isdst=-1) # 將時間結構體轉換為時間戳 t = time.mktime(t) print(t) #1637391276.0
example2:
import time t = "Mon Mar 16 00:09:00 +0000 2015" t = time.strptime(t, "%a %b %d %H:%M:%S %z %Y") # 將時間結構體轉換為時間戳 t = time.mktime(t) # 1426435740.0 print(t)
strftime()中各個字母的含義
年 %Y Year with century as a decimal number. 月 %m Month as a decimal number [01,12]. 日 %d Day of the month as a decimal number [01,31]. 小時 %H Hour (24-hour clock) as a decimal number [00,23]. 分鍾 %M Minute as a decimal number [00,59]. 秒 %S Second as a decimal number [00,61]. 時區 %z Time zone offset from UTC. %a Locale's abbreviated weekday name. %A Locale's full weekday name. %b Locale's abbreviated month name. %B Locale's full month name. %c Locale's appropriate date and time representation. 小時(12小時制)%I Hour (12-hour clock) as a decimal number [01,12]. %p Locale's equivalent of either AM or PM.