数字,日期,时间

1、我们想将一个浮点数取整到固定的小数位

使用内建的round(value,ndigits)即可:

1 >>> round(1.23,1)
2 1.2
3 >>> round(1.27,1)
4 1.3
5 >>> round(-1.27,1)
6 -1.3
7 >>> round(1.1231237,3)
8 1.123
9 >>> 

ndigits可以是负数,这样的情况下会相应的取整到十位,百位千位等,如:

 1 >>> round(1.1231237,3)
 2 1.123
 3 >>> a = 1231231
 4 >>> round(a,-1)
 5 1231230
 6 >>> round(a,-2)
 7 1231200
 8 >>> round(a,-3)
 9 1231000
10 >>> 

对值的输出时,不能把取整与格式化输出混为一谈,如果只是让数值以固定的位数输出,一般不用round():

1 >>> x = 1.23456
2 >>> format(x,'0.2f')
3 '1.23'
4 >>> format(x,'0.3f')
5 '1.235'
6 >>> 'value is {:0.3f}'.format(x)
7 'value is 1.235'

执行精确的小数运算,我们先来看下面的小例子:

1 >>> a = 4.2
2 >>> b = 2.1
3 >>> a + b
4 6.300000000000001
5 >>> (a + b) == 6.3
6 False
7 >>> 

居然是False,这些误差实际上是底层CPU的浮点运算单元和IEEE754浮点运算术标准的一种特性,那么如何避免这样的误差,得到更高的精度呢(会牺一点性能),可以使用decimal模块

 1 >>> from decimal import Decimal
 2 >>> a = Decimal(4.2)
 3 >>> b = Decimal(2.1)
 4 >>> a + b
 5 Decimal('6.300000000000000266453525910')
 6 >>> print(a + b)
 7 6.300000000000000266453525910
 8 >>> a = Decimal('4.2')
 9 >>> b = Decimal('2.1')
10 >>> a + b
11 Decimal('6.3')
12 >>> print(a + b)
13 6.3
14 >>> (a + b) == 6.3
15 False
16 >>> (a + b) == Decimal('6.3')
17 True
18 >>> 

注意引号

 时间转换

#_*_coding:utf-8_*_
import time
import datetime
 
print(time.clock()) #返回处理器时间,3.3开始已废弃
print(time.process_time()) #返回处理器时间,3.3开始已废弃
print(time.time()) #返回当前系统时间戳
print(time.ctime()) #输出Tue Jan 26 18:23:48 2016 ,当前系统时间
print(time.ctime(time.time()-86640)) #将时间戳转为字符串格式
print(time.gmtime(time.time()-86640)) #将时间戳转换成struct_time格式
print(time.localtime(time.time()-86640)) #将时间戳转换成struct_time格式,但返回 的本地时间
print(time.mktime(time.localtime())) #与time.localtime()功能相反,将struct_time格式转回成时间戳格式
#time.sleep(4) #sleep
print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将struct_time格式转成指定的字符串格式
print(time.strptime("2016-01-28","%Y-%m-%d") ) #将字符串格式转换成struct_time格式
 
#datetime module
 
print(datetime.date.today()) #输出格式 2016-01-26
print(datetime.date.fromtimestamp(time.time()-864400) ) #2016-01-16 将时间戳转成日期格式
current_time = datetime.datetime.now() #
print(current_time) #输出2016-01-26 19:04:30.335935
print(current_time.timetuple()) #返回struct_time格式
 
#datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
print(current_time.replace(2014,9,12)) #输出2014-09-12 19:06:24.074900,返回当前时间,但指定的值将被替换
 
str_to_date = datetime.datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M") #将字符串转换成日期格式
new_date = datetime.datetime.now() + datetime.timedelta(days=10) #比现在加10天
new_date = datetime.datetime.now() + datetime.timedelta(days=-10) #比现在减10天
new_date = datetime.datetime.now() + datetime.timedelta(hours=-10) #比现在减10小时
new_date = datetime.datetime.now() + datetime.timedelta(seconds=120) #比现在+120s
print(new_date)

原文地址:https://www.cnblogs.com/zcx-python/p/5573956.html