本节内容
1、datetime.datetime.now
2、datetime.date.fromtimestamp
3、datetime.timedelta
4、时间替换
1、datetime.datetime.now()
功能:返回当前时间,格式如:2016-08-19 12:47:03.941925
1
2
3
|
>>> import datetime >>> print (datetime.datetime.now()) 2017 - 03 - 31 10 : 22 : 09.819373 |
2、datetime.date.fromtimestamp()
功能:时间戳转换为日期格式
1
2
3
4
|
>>> import datetime,time >>> t = datetime.date.fromtimestamp(time.time()) >>> print (t) #把当天日期的时间戳转换为当天日期 2017 - 03 - 31 |
3、datetime.timedelta()
功能:对某个时间的加减
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
>>> import datetime #当前时间加3天 >>> t1 = datetime.datetime.now() + datetime.timedelta(days = 3 ) >>> print (t1) 2017 - 04 - 03 10 : 42 : 50.714910 #当前时间减3天 >>> t1 = datetime.datetime.now() - datetime.timedelta(days = 3 ) >>> print (t1) 2017 - 03 - 28 10 : 43 : 17.260111 #当前时间减3天 >>> t1 = datetime.datetime.now() + datetime.timedelta(days = - 3 ) >>> print (t1) 2017 - 03 - 28 10 : 43 : 35.758742 #当前时间加3个小时 >>> t1 = datetime.datetime.now() + datetime.timedelta(hours = 3 ) >>> print (t1) 2017 - 03 - 31 13 : 44 : 24.805354 #当前时间加30分钟 >>> t1 = datetime.datetime.now() + datetime.timedelta(minutes = 30 ) >>> print (t1) 2017 - 03 - 31 11 : 14 : 55.990195 |
4、时间替换
1
2
3
4
5
6
7
8
9
10
|
>>> import datetime >>> c_time = datetime.datetime.now() #当前时间输出 >>> print (c_time) 2017 - 03 - 31 10 : 47 : 22.682289 #时间替换 >>> update_c_time = c_time.replace(minute = 3 ,hour = 2 ) #替换后的时间输出 >>> print (update_c_time) 2017 - 03 - 31 02 : 03 : 22.682289 |