1. 程式人生 > >time和datetime模塊

time和datetime模塊

計算機 classname color library document 參數 span ber hour

time模塊:

技術分享

Timestamp:計算機中時間是由數字表示的。將1970.1.1 00:00:00 UTC+00:00時區的時刻稱為epoch time,記為0(1970年以前的timestamp為負數),當前的時間就是相對 於epoch time的秒數,稱為timestamp。

In [109]: time.time()
Out[109]: 1510054096.087551

struct time:time.gmtime([secs]) 返回UTC時間,dst=0,secs默認為當前時間戳

      time.localtime([secs])返回本地時間UTC+8,dst=0,secs默認為當前時間戳

In [108]: time.gmtime()
Out[108]: time.struct_time(tm_year=2017, tm_mon=11, tm_mday=7, tm_hour=11, tm_min=26, tm_sec=3, tm_wday=1, tm_yday=311, tm_isdst=0)
In [107]: time.localtime()
Out[107]: time.struct_time(tm_year=2017, tm_mon=11, tm_mday=7, tm_hour=19, tm_min=25, tm_sec=52, tm_wday=1, tm_yday=311, tm_isdst=0
)

mktime(tuple) -> floating point number

In [113]: t=time.localtime()
In [115]: time.mktime(t)
Out[115]: 1510054321.0

time.ctime([secs])返回本地時間,secs默認為time.time()

time.asctime([t])將表示由gmtime()localtime()返回的時間的元組或struct_time轉換為以下形式字符串 。若未提供t,則使用localtime()返回的當前時間。

In [104]: time.ctime()
Out[104]: 
Tue Nov 7 19:08:51 2017 In [105]: time.asctime() Out[105]: Tue Nov 7 19:08:56 2017

time.strftime(format[, t])gmtime()localtime()返回的時間元組或struct_time轉為由格式指定的字符串參數。若未提供t,用localtime()返回的當前時間。格式必須是字符串。

time.strptime(string[, format])根據格式解析表示時間的字符串。返回值是由gmtime()localtime()返回的struct_time

In [116]: time.strftime(%Y-%m-%d)
Out[116]: 2017-11-07

In [117]: time.strptime(2017-11-07,%Y-%m-%d)
Out[117]: time.struct_time(tm_year=2017, tm_mon=11, tm_mday=7, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=311, tm_isdst=-1)

time.sleep(secs)延遲

附表:

技術分享

技術分享

技術分享

datetime模塊:

獲取當前日期及時間:

In [118]: from datetime import datetime
In [119]: now = datetime.now()

In [121]: print(now)
2017-11-07 20:06:04.360664

In [123]: print(type(now))
<class ‘datetime.datetime‘>

獲取指定日期及時間:

In [124]: dt = datetime(2017,11,4,7,20,30)
In [125]: print(dt)
2017-11-04 07:20:30

datetime-->timestamp:

In [126]: dt.timestamp()
Out[126]: 1509751230.0

timestamp-->datetime:

In [127]: t=1490001234.0
In [128]: print(datetime.fromtimestamp(t))        #本地時間
2017-03-20 17:13:54

In [129]: print(datetime.utcfromtimestamp(t))     #UTC時間
2017-03-20 09:13:54

str-->datetime:

In [130]: cday = datetime.strptime(2017-6-4 15:30:45,%Y-%m-%d %H:%M:%S)

In [131]: print(cday,type(cday))
2017-06-04 15:30:45 <class datetime.datetime>

datetime-->str:

In [132]: print(now.strftime(%a, %b %d %H:%M))
Tue, Nov 07 20:06

datetime加減:

In [133]: from datetime import timedelta

In [134]: now = datetime.now()

In [135]: now
Out[135]: datetime.datetime(2017, 11, 7, 20, 36, 8, 36987)

In [136]: now + timedelta(hours=10)
Out[136]: datetime.datetime(2017, 11, 8, 6, 36, 8, 36987)

In [137]: now + timedelta(days=1)
Out[137]: datetime.datetime(2017, 11, 8, 20, 36, 8, 36987)

In [138]: now - timedelta(days=3,hours=14)
Out[138]: datetime.datetime(2017, 11, 4, 6, 36, 8, 36987)

time和datetime模塊