1. 程式人生 > >時間模塊

時間模塊

code res cpu second real 得到 bsp rop false

time模塊

在time模塊中,time.time()和time.sleep()函數是最有用的模塊。

time.time()函數返回自那一刻以來的秒數,是一個浮點值。

可以通過兩次調用time.time(),相減後得到這兩次調用之間經過的時間。也可以采用cProfile.run()函數剖析代碼。

>>> import time
>>> dir(time)
['CLOCK_MONOTONIC', 'CLOCK_MONOTONIC_RAW', 'CLOCK_PROCESS_CPUTIME_ID', 'CLOCK_REALTIME', 'CLOCK_THREAD_CPUTIME_ID', '_STRUCT_TM_ITEMS', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'altzone', 'asctime', 'clock', 'clock_getres', 'clock_gettime', 'clock_settime', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 'mktime', 'monotonic', 'perf_counter', 'process_time', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'timezone', 'tzname', 'tzset']
>>> time.time()
1518951868.44606
>>> t1=time.time()
>>> t=time.time()-t1
>>> print(t)
20.188032150268555


如果需要讓函數暫停一下,就調用time.sleep()函數,並傳入希望程序暫停的秒數。

在IDLE中按Ctrl-C不會中斷time.sleep()調用。IDLE會等待到暫停結束,再拋出KeyboardInterrupt異常。

利用一個while循環,配合time.sleep()函數,可以讓程序暫停,直到一個特定的日期。

>>> import time
>>> for i in range(3):
...     print(time.time())
...     time.sleep(1)
...     print(time.time())
...     time.sleep(10)
... 
1518952469.0750868
1518952470.076255
1518952480.08646
1518952481.0876613
1518952491.097851
1518952492.0990806
>>>


使用內置的round()函數可以進行數字的四舍五入,可以精確控制時間的精度。

>>> import time
>>> now=time.time()
>>> now
1518952700.4760277
>>> round(now,2)
1518952700.48
>>> round(now,4)
1518952700.476
>>> round(now)
1518952700


datetime模塊

從time模塊中,可以看到時間可讀性較差。datetime模塊能以更方便的格式顯示日期,或對日期進行算數運算。

datetime模塊有自己的datetime數據類型。datetime值表示一個特定的時刻。

datetime對象可以用比較操作符進行比較,得到True/False值。

unix紀元時間戳可以通過datetime.datetime.fromtimestamp(),轉換為datetime對象。datetime對象的日期和時間將根據本地時區轉換。

>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2018, 2, 18, 19, 22, 32, 105656)
>>> dt=datetime.datetime(2088,8,8,18,28,38,0)
>>> dt.year,dt.month,dt.day
(2088, 8, 8)
>>> dt.hour,dt.minute,dt.second
(18, 28, 38)
>>> datetime.datetime.now() > dt
False


datetime模塊還提供了timedelta數據類型,它表示一段時間,而不是一個時刻。

>>> import datetime
>>> delta=datetime.timedelta(days=11,hours=10,minutes=9,seconds=8)
>>> delta.days,delta.seconds,delta.microseconds
(11, 36548, 0)
>>> delta.total_seconds()
986948.0
>>> str(delta)
'11 days, 10:09:08'


算數運算符可以對datetime值進行日期運算。

利用+和-運算符,timedelta對象與datetime對象或其他timedelta對象相加或相減。

利用*和/運算符,timedelta對象可以乘以或除以整數或浮點數。

>>> import datetime
>>> dt=datetime.datetime.now()
>>> dt
datetime.datetime(2018, 2, 18, 19, 33, 22, 97390)
>>> thousandDays=datetime.timedelta(days=1000)
>>> dt+thousandDays
datetime.datetime(2020, 11, 14, 19, 33, 22, 97390)
>>> dt+(2*thousandDays)
datetime.datetime(2023, 8, 11, 19, 33, 22, 97390)


利用strftime()方法,可以將datetime對象顯示為字符串。

strptime()函數與strftime()方法相反。

DirectiveMeaningExample
%aWeekday as locale’s abbreviated name.

Sun, Mon, …, Sat (en_US);

So, Mo, …, Sa (de_DE)

%AWeekday as locale’s full name.

Sunday, Monday, …, Saturday (en_US);

Sonntag, Montag, …, Samstag (de_DE)

%wWeekday as a decimal number, where 0 is Sunday and 6 is Saturday.0, 1, …, 6
%dDay of the month as a zero-padded decimal number.01, 02, …, 31
%bMonth as locale’s abbreviated name.

Jan, Feb, …, Dec (en_US);

Jan, Feb, …, Dez (de_DE)

%BMonth as locale’s full name.

January, February, …, December (en_US);

Januar, Februar, …, Dezember (de_DE)

%mMonth as a zero-padded decimal number.01, 02, …, 12
%yYear without century as a zero-padded decimal number.00, 01, …, 99
%YYear with century as a decimal number.0001, 0002, …, 2013, 2014, …, 9998, 9999
%HHour (24-hour clock) as a zero-padded decimal number.00, 01, …, 23
%IHour (12-hour clock) as a zero-padded decimal number.01, 02, …, 12
%pLocale’s equivalent of either AM or PM.

AM, PM (en_US);

am, pm (de_DE)

%MMinute as a zero-padded decimal number.00, 01, …, 59
%SSecond as a zero-padded decimal number.00, 01, …, 59
%fMicrosecond as a decimal number, zero-padded on the left.000000, 000001, …, 999999
%zUTC offset in the form +HHMM or -HHMM (empty string if the object is naive).(empty), +0000, -0400, +1030
%ZTime zone name (empty string if the object is naive).(empty), UTC, EST, CST
%jDay of the year as a zero-padded decimal number.001, 002, …, 366
%UWeek number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0.00, 01, …, 53
%WWeek number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0.00, 01, …, 53
%cLocale’s appropriate date and time representation.

Tue Aug 16 21:30:00 1988 (en_US);

Di 16 Aug 21:30:00 1988 (de_DE)

%xLocale’s appropriate date representation.

08/16/88 (None);

08/16/1988 (en_US);

16.08.1988 (de_DE)

%XLocale’s appropriate time representation.

21:30:00 (en_US);

21:30:00 (de_DE)

%%A literal '%' character.%
>>> import datetime
>>> dt20180218=datetime.datetime.now()
>>> dt20180218.strftime('%Y/%m/%d %H:%M:%S')
'2018/02/18 19:45:13'
>>> dt20180218.strftime('%I:%M %p')
'07:45 PM'
>>> dt20180218.strftime('%B of %y')
'February of 18'
>>> datetime.datetime.strptime('February 18,2018','%B %d,%Y')
datetime.datetime(2018, 2, 18, 0, 0)


時間模塊