1. 程式人生 > 實用技巧 >time與datatime模組,

time與datatime模組,

一、time模組

1、時間有三種格式(*****)

# 1、時間戳:秒數=>用於時間計算(得到的是浮點型,用於加減乘除運算)
start=time.time()
print(start,type(start)) #1596367382.30072 <class 'float'>

# 2、格式化的字串=>用於顯示給人看(得到的是字串型別,可用於寫到檔案中)
res=time.strftime("%Y-%m-%d %H:%S:%M %p")
res=time.strftime("%Y-%m-%d %X")
print(res,type(res)) #2020-08-02 19:23:02 <class 'str'>
# 3、結構化的時間=>獲取時間的某一部分(以此可以按照當前的時間計算出另外一個時間) res = time.localtime() res1 = time.gmtime() #不同之處就是localtime按照東八區計時(中國時間),gmtime以國際標準計算時間,英國本初子午線劃分 print(res) #time.struct_time(tm_year=2020, tm_mon=8, tm_mday=2, tm_hour=19, tm_min=23, tm_sec=2, tm_wday=6, tm_yday=215, tm_isdst=0) print(res1) #time.struct_time(tm_year=2020, tm_mon=8, tm_mday=2, tm_hour=11, tm_min=23, tm_sec=2, tm_wday=6, tm_yday=215, tm_isdst=0)
print(type(res)) #<class 'time.struct_time'> print(res.tm_year)#選出其中一個 這裡選出的是年 #打印出 2020

2、時間格式轉換

# 2.1 時間戳---》格式化的字串
struct_time=time.localtime(3333.3)  #time.localtime()不傳值預設就是time.time()
res=time.strftime("%Y-%m",struct_time)
print(res) #1970-01

# 2.2 格式化的字串---》時間戳
struct_time=time.strptime("
2017-07-03 11:11:11","%Y-%m-%d %H:%M:%S") res=time.mktime(struct_time) print(res) #1499051471.0

3、

print(time.ctime(3333.3)) # Thu Jan  1 08:55:33 1970  #time.ctime()不傳值預設就是time.time()
print(time.asctime(time.localtime(3333.3))) #Thu Jan  1 08:55:33 1970

4、

time.sleep(3) #括號內傳秒

二、datetime模組

import datetime

res=datetime.datetime.now()
print(res) #直接獲取當前時間

print(datetime.date.fromtimestamp(time.time())) #時間戳直接轉成日期格式 2020-08-02
print(datetime.datetime.fromtimestamp(time.time())) #2020-08-02 19:55:15.371285
#舉例:計算三天前/三天後
res=datetime.datetime.now() + datetime.timedelta(days=3)
res=datetime.datetime.now() + datetime.timedelta(days=-3)
print(res)
#當前時間
res=datetime.datetime.now()
print(res)
#以當前時間為基準,把年/月/日等換掉
new_res=res.replace(year=1999,month=9)
print(new_res)
-------------------------------------------------------------------------------------------------
# print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925
#print(datetime.date.fromtimestamp(time.time()) )  # 時間戳直接轉成日期格式 2016-08-19
# print(datetime.datetime.now() )
# print(datetime.datetime.now() + datetime.timedelta(3)) #當前時間+3天
# print(datetime.datetime.now() + datetime.timedelta(-3)) #當前時間-3天
# print(datetime.datetime.now() + datetime.timedelta(hours=3)) #當前時間+3小時
# print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #當前時間+30分


# c_time  = datetime.datetime.now()
# print(c_time.replace(minute=3,hour=2)) #時間替換