python的date和datetime模塊


#__Author: "Skiler Hao"
#date: 2017/2/15 11:06
"""
主要是測試和練習時間模塊的使用

時間主要有字符串格式、時間戳 和 結構化時間元祖

一、date模塊

字符串模式:Wed Feb 15 11:40:23 2017
時間戳格式:1463846400.0
結構化時間元祖:time.struct_time(tm_year=2017, tm_mon=2, tm_mday=15, tm_hour=11, tm_min=40, tm_sec=23, tm_wday=2, tm_yday=46, tm_isdst=0)

時間元祖是時間類型轉化的關鍵
"""

import datetime
import time

#獲取當前的時間,以三種格式展示出來

 

 

print(time.asctime()) #返回時間字符串Wed Feb 15 11:15:21 2017

print(time.localtime()) # 返回的是<class 'time.struct_time'>,例如time.struct_time(tm_year=2017, tm_mon=2, tm_mday=15, tm_hour=11, tm_min=21, tm_sec=2, tm_wday=2, tm_yday=46, tm_isdst=0)
print(type(time.time())) #返回的是float類型的當前時間戳

time.ctime()

#--------------時間類型轉換
string_2_struct = time.strptime("2016/05/22","%Y/%m/%d") #將字符串轉化成時間元祖
print(time.gmtime(time.time())) #將時間戳轉換成時間元祖格式


struct_2_stamp = time.mktime(string_2_struct) #將時間元祖轉化成時間戳
print(struct_2_stamp)


print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #將utc struct_time格式轉成指定的字符串格式


#------------其他用途的時間函數
print(time.process_time()) #處理器計算時間
time.sleep(2) #睡眠指定的時間

 

二、datetime模塊的使用和說明

datetime是基於time模塊封裝的,使用起來更加友好,但是執行效率略低。datetime里有四個重要的類:datetime、date、time、timedelta

1、datetime類:

  創建datetime對象:

    datetime.datetime (year, month, day[ , hour[ , minute[ , second[ , microsecond[ , tzinfo] )

    datetime.fromtimestamp(cls, timestamp, tz=None)

     datetime.utcfromtimestamp(cls, timestamp)

    datetime.now(cls, tz=None)

    datetime.utcnow(cls)

    datetime.combine(cls, datetime.date, datetime.time)

  datetime的實例方法:

    datetime.year、month、day、hour、minute、second、microsecond、tzinfo:
    datetime.date():獲取date對象;
    datetime.time():獲取time對象;
    datetime. replace ([ year[ , month[ , day[ , hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] ] ] ] ]):
    datetime. timetuple ()
    datetime. utctimetuple ()
    datetime. toordinal ()
    datetime. weekday ()
    datetime. isocalendar ()
    datetime. isoformat ([ sep] )
    datetime. ctime ():返回一個日期時間的C格式字符串,等效於time.ctime(time.mktime(dt.timetuple()));
    datetime. strftime (format)

2、timedelta類

 

 

 

#-------------------------計算相識時間-------------
def firstTimeToNow():
now = datetime.datetime.now()
first_time_tuple = datetime.datetime.strptime("2017/01/24","%Y/%m/%d")
return (now - first_time_tuple).days
print("相見相識,第"+str(firstTimeToNow())+"天")

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM