记录博客 ZH-BLOG

Python 时间模块

时间:2018-07-23 17:26:05分类:python

time.time()函数

>>> import time
>>> time.time()
1532333561.4832551
>>> round(time.time())
1532333568
>>> round(time.time(), 2)
1532333575.61

计算方法运行的时间

>>> def ts():
	t1 = time.time()
	time.sleep(3) # 睡眠 3s
	t2 = time.time()
	print('total: %s'% (t2 - t1))

	
>>> ts()
total: 3.000171661376953

datetime 模块

datetime 值表示一个特定的时刻,更方便的格式显示日期,或对日期进行算术运算,应该使用 datetime 模块。

>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2018, 7, 23, 16, 21, 42, 748213)
>>> datetime.datetime(2018, 10, 1, 10, 10, 1, 234)
datetime.datetime(2018, 10, 1, 10, 10, 1, 234)
>>> dt = datetime.datetime(2018, 10, 1, 10, 10, 1, 234)
>>> dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second
(2018, 10, 1, 10, 10, 1)
>>> datetime.datetime.fromtimestamp(1000*60*60)
datetime.datetime(1970, 2, 12, 0, 0)
>>> datetime.datetime.fromtimestamp(1000000)
datetime.datetime(1970, 1, 12, 21, 46, 40)
>>> datetime.datetime.fromtimestamp(60*60*24)
datetime.datetime(1970, 1, 2, 8, 0)
>>> datetime.datetime.fromtimestamp(time.time())
datetime.datetime(2018, 7, 23, 16, 53, 6, 260944)
>>> t1 = datetime.datetime(2016, 10, 10)
>>> t2 = datetime.datetime(2017, 1, 1)
>>> t2>t1
True
>>> t2-t1
datetime.timedelta(83)

timedelta 表示一段时间,而不是一个时刻

>>> td = datetime.timedelta(days=7, hours=2, seconds=30)
>>> td
datetime.timedelta(7, 7230)
>>> td.total_seconds()
612030.0
>>> str(td)
'7 days, 2:00:30'
>>> td.days, td.seconds # 只有两个有用属性:总天数,(除天总)秒数
(7, 7230)
>>> td.microseconds
0
>>> n = datetime.datetime.now() - td
>>> n
datetime.datetime(2018, 7, 16, 15, 17, 3, 35839)

格式化时间

>>> dt = datetime.datetime.now()
>>> dt.strftime('%Y-%m-%d %H:%M:%S')
'2018-07-23 17:22:00'

字符串转换成 datetime 对象

>>> datetime.datetime.strptime('2018-10-10','%Y-%m-%d')
datetime.datetime(2018, 10, 10, 0, 0)
>>> datetime.datetime.strptime('2018-10-10 12:12:10','%Y-%m-%d')
Traceback (most recent call last):
  File "", line 1, in 
    datetime.datetime.strptime('2018-10-10 12:12:10','%Y-%m-%d')
  File "D:\work\Python\Python36\lib\_strptime.py", line 565, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "D:\work\Python\Python36\lib\_strptime.py", line 365, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains:  12:12:10
>>> datetime.datetime.strptime('2018-10-10 12:12:10','%Y-%m-%d %H:%M:%S')
datetime.datetime(2018, 10, 10, 12, 12, 10)