标准库time、datetime、calendar、random的使用

1. 时间戳: 格林威治时间1970年01月01日00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。
2.元组struct_time: 日期、时间是包含许多变量的,所以在Python中定义了一个元组struct_time将所有这些变量组合在一起,包括:4位数年、月、日、小时、分钟、秒等。

所有变量及要求如下:

序号属性
0tm_year(4位年数)2019
1tm_mon(月)1-12
2tm_mday(日)1-31
3tm_hour(小时)0-23
4tm_min(分钟)0-59
5tm_sec(秒)0-61(61是闰秒)
6tm_wday(一周的第几天)0-6(0是周一)
7tm_yday(一年的第一天)1-366
8tm_isdst(夏令时)-1, 0, 1, -1是决定是否为夏令时的旗帜

一、time模块

1.time.time():
返回当前时间的时间戳(1970纪元后经过的浮点秒数)。

>>> time.time()
15**54727187.779613

2. time.gmtime():
获取当前时间,返回计算机可处理的时间格式, 以UTC的时间计

>>> time.gmtime()
time.struct_time(tm_year=2019, tm_mon=4, tm_mday=8, tm_hour=12, tm_min=42, tm_sec=42, tm_wday=0, tm_yday=98, tm_isdst=0)

3.time.localtime():
获取计算机当前时间,以当地时间计

>>> time.localtime()
time.struct_time(tm_year=2019, tm_mon=4, tm_mday=8, tm_hour=20, tm_min=44, tm_sec=6, tm_wday=0, tm_yday=98, tm_isdst=0)

4. time.asctime():
函数接受时间元组并返回一个可读的形式为"Mon Apr 8 20:47:24 2019"(2019年4月8日 周一20时47分24秒)的24个字符的字符串。

>>> time.asctime(time.localtime())
'Mon Apr  8 20:47:24 2019'

5. time.ctime() :
把一个时间戳(按秒计算的浮点数)转化为time.asctime()的形式。 如果参数未给或者为None的时候,将会默认time.time()为参数。它的作用相当于 asctime(localtime(secs))。

>>> time.ctime()
'Mon Apr  8 20:50:32 2019'

6. time.mktime():
函数执行与gmtime(), localtime()相反的操作,它接收struct_time对象作为参数,返回用秒数来表示时间的浮点数。
如果输入的值不是一个合法的时间,将触发 OverflowError 或 ValueError。

>>> t = (2019,4,8,20,4,6,0,98,0)
>>> t1 = time.mktime(t)
>>> t1
1554725046.0

7.time.sleep(t):
函数推迟调用线程的运行,可通过参数secs指秒数,表示进程挂起的时间。
没有返回值
8. time.strftime():
函数接收以时间元组,并返回以可读字符串表示的当地时间,格式由参数format决定

python中时间日期格式化符号:

符号内容
%y两位数的年份表示(00-99)
%Y四位数的年份表示(000-9999)
%m月份(01-12)
%d月内中的一天(0-31)
%H24小时制小时数(0-23)
%I12小时制小时数(01-12)
%M分钟数(00=59)
%S秒(00-59)
%a本地简化星期名称
%A本地完整星期名称
%b本地简化的月份名称
%B本地完整的月份名称
%c本地相应的日期表示和时间表示
%j年内的一天(001-366)
%p本地A.M.或P.M.的等价符
%U一年中的星期数(00-53)星期天为星期的开始
%w星期(0-6),星期天为星期的开始
%W一年中的星期数(00-53)星期一为星期的开始
%x本地相应的日期表示
%Z当前时区的名称
%%%号本身
>>> time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
'2019-04-08 21:26:34'

9.time.strptime():
函数根据指定的格式把一个时间字符串解析为时间元组。

>>> time.strptime('2019-04-08 21:26:34','%Y-%m-%d %H:%M:%S')
time.struct_time(tm_year=2019, tm_mon=4, tm_mday=8, tm_hour=21, tm_min=26, tm_sec=34, tm_wday=0, tm_yday=98, tm_isdst=-1)

二、datetime模块

datetime模块用于是date和time模块的合集,datetime有两个常量,MAXYEAR和MINYEAR,分别是9999和1.

>>> import datetime
>>> datetime.MAXYEAR
9999

>>> datetime.MINYEAR
1

1.datetime.date类:

date类有三个参数,datetime.date(year,month,day),返回year-month-day

  • 通过year, month, day三个数据描述符可以进行访问:
>>> a.day
11
>>> a = datetime.date.today()
>>> a
datetime.date(2019, 4, 11)
>>> a.year
2019
>>> a.month
4
>>> a.day
11
  • 用__getattribute__(…)方法获得年,月,日:
>>> a.__getattribute__('year')
2019
>>> a.__getattribute__('month')
4
>>> a.__getattribute__('day')
11
  • 常用方法:
方法名方法说明用法
eq(…)等于(x==y)x.eq(y)
ge(…)大于等于(x>=y)x.ge(y)
gt(…)大于(x>y)x.gt(y)
le(…)小于等于(x<=y)x.le(y)
lt(…)小于(x<y)x.lt(y)
ne(…)不等于(x!=y)x.ne(y)
sub(…)x - yx.sub(y)
rsub(…)y - xx.rsub(y)

返回值为True或False

>>> a = datetime.date(2018,1,2)
>>> b = datetime.date(2019,1,1)

>>> a.__eq__(b)
False
>>> a.__ge__(b)
False
>>> a.__gt__(b)
False
>>> a.__le__(b)
True
>>> a.__lt__(b)
True
>>> a.__ne__(b)
True

>>> a.__sub__(b)
datetime.timedelta(-364)
>>> a.__rsub__(b)
datetime.timedelta(364)
  • ISO标准化日期:

(1) datetime.date.isocalendar() 返回格式如(year,month,day)的元组

>>> a = datetime.date.today()
>>> a.isocalendar()
(2019, 15, 4)
>>> a.isocalendar()[0]
2019
>>> a.isocalendar()[1]
15
>>> a.isocalendar()[2]
4

(2) datetime.date.isoformat(): 返回格式如YYYY-MM-DD

>>> a = datetime.date.today()
>>> a.isoformat()
'2019-04-11'

(3) datetime.date.isoweekday(): 返回给定日期的星期(0-6),星期一=1,星期日=7

>>> a = datetime.date(2019,4,1)
>>> a.isoweekday()
1

(4) weekday(…): 星期一=0,星期日=6

>>> a = datetime.date(2019,4,1)
>>> a.weekday()
0
  • 其他方法与属性:

(1)**today(…):**返回当前日期

>>> datetime.date.today()
datetime.date(2019, 4, 11)

(2)datetime.date.timetuple(): 返回日期对应的time.struct_time对象

>>> a = datetime.date(2019,4,1)
>>> a.timetuple()
time.struct_time(tm_year=2019, tm_mon=4, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=91, tm_isdst=-1)

(3) ** toordinal(…):** 返回公元公历开始到现在的天数。公元1年1月1日为1

>>> a = datetime.date.today()
>>> a.toordinal()
737160

(4)datetime.date.replace(year,month,day): 替换给定日期,但不改变原日期

>>> a = datetime.date(2019,4,1)
>>> b = a.replace(2018,12,12)
>>> a
datetime.date(2019, 4, 1)
>>> b
datetime.date(2018, 12, 12)

(5)resolution:date对象表示日期的最小单位。这里是天

>>> datetime.date.resolution
datetime.timedelta(1)

(6)fromtimestamp(…): 根据给定的时间戮,返回一个date对象

>>> time.time()
1554983927.9255753
>>> datetime.date.fromtimestamp(time.time())
datetime.date(2019, 4, 11)

(7)max: date类能表示的最大的年、月、日的数值

>>> datetime.date.max
datetime.date(9999, 12, 31)

(8)min: date类能表示的最小的年、月、日的数值

>>> datetime.date.min
datetime.date(1, 1, 1)
  • 日期的字符串输出:

(1)将日期对象转化为字符串对象的话,可以用到__format__(…)方法以指定格式进行日期输出:

>>> a = datetime.date(2019,4,1)
>>> a.__format__('%Y-%m-%d')
'2019-04-01'
# 等价于
>>> a.strftime("%Y-%m-%d")
'2019-04-01'

>>> a.__format__('%Y/%m/%d')
'2019/04/01'
>>> a.__format__('%y/%m/%d')
'19/04/01'
>>> a.__format__('%D')
'04/01/19'

(2)获得日期的字符串,则使用__str__(…)

>>> a.__str__()
'2019-04-01'

(3)获得ctime样式的格式请使用ctime(…):

>>> a.ctime()
'Mon Apr  1 00:00:00 2019'

2.datetime.time类

time类有5个参数,datetime.time(hour,minute,second,microsecond,tzoninfo)
(hour小时、minute分钟、second秒、microsecond毫秒和tzinfo)

>>> a = datetime.time(20,12,59,899)
>>> a.hour      # 等价 a.__getattribute__('hour')
	       
20
>>> a.minute  #等价 a.__getattribute__('minute')
12

>>> a.second # 等价 a.__getattribute__('second')
59

>>> a.microsecond
899
  • 方法和属性
    方法与date类中定义的方法差不多
>>> a = datetime.time(13,21,59,899)
>>> b = datetime.time(11,27,59,889)
>>> a.__eq__(b)
False
>>> a.__ne__(b)
True
>>> a.__ge__(b)
True
>>> a.__gt__(b)
True
>>> a.__le__(b)
False
>>> a.__lt__(b)
False

>>> datetime.time.max    # 最大的时间表示数值:
datetime.time(23, 59, 59, 999999)
>>> datetime.time.min   # 最小的时间表示数值
datetime.time(0, 0)

+时间的字符串输出
(1)将时间对象转化为字符串对象的话,可以用到__format__(…)方法以指定格式进行时间输出:

>>> a = datetime.time(20,12,00,899)
>>> a.__format__('%H:%M:%S')
'20:12:00'
# 等价于
>>> a.strftime('%H:%M:%S')
'20:12:00'

(2)获得时间的字符串,使用__str__(…)

>>> a.__str__()
'20:12:00.000899'

3.datetime.datetime类

datetime类有很多参数,datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]]),返回年月日,时分秒
(datetime类其实是可以看做是date类和time类的合体,其大部分的方法和属性都继承于这二个类)

  • 专属于datetime的方法和属性

(1)date(…):返回datetime对象的日期部分:

>>> a = datetime.datetime.now()
>>> a
datetime.datetime(2019, 4, 11, 21, 22, 49, 791136)
>>> a.date()
datetime.date(2019, 4, 11)

(2)time(…):返回datetime对象的时间部分:

 a = datetime.datetime.now()
>>> a.time()
datetime.time(21, 22, 49, 791136)

(3)**utctimetuple(…):**返回UTC时间元组:

>>> a = datetime.datetime.now()
>>> a.utctimetuple()
time.struct_time(tm_year=2019, tm_mon=4, tm_mday=11, tm_hour=21, tm_min=26, tm_sec=2, tm_wday=3, tm_yday=101, tm_isdst=0)

(4)**combine(…):**将一个date对象和一个time对象合并生成一个datetime对象:

>>> a = datetime.datetime.now()
>>> datetime.datetime.combine(a.date(),a.time())
datetime.datetime(2019, 4, 11, 21, 27, 26, 577929)

(5)now(…):返回当前日期时间的datetime对象:

>>> a = datetime.datetime.now()
>>> a
datetime.datetime(2019, 4, 11, 21, 28, 14, 295336)`

(6)utcnow(…): 返回当前日期时间的UTC datetime对象:

>>> a = datetime.datetime.utcnow()
>>> a
datetime.datetime(2019, 4, 11, 13, 30, 10, 102200)

(7)strptime(…): 根据string, format 2个参数,返回一个对应的datetime对象:

>>> datetime.datetime.strptime('2019-4-1 12:20','%Y-%m-%d %H:%M')
datetime.datetime(2019, 4, 1, 12, 20)

4.datetime.timedelta类

用于计算两个日期之间的差值

>>> a = datetime.datetime(2019,4,11)
>>> b = datetime.datetime(2012,4,8)
>>> (a-b).days  # 计算日期的间隔天数 
 2559
>>> (a-b).total_seconds()  # 计算日期的间隔秒数
221097600.0

三、calendar模块

此模块的函数都是日历相关的,例如打印某月的字符月历。

1.calendar.calendar(): calendar.calendar()

import calendar
calendar.calendar(2019)


2.calendar.month(): calendar.month()

>>> calendar.month(2019,4)
'     April 2019\nMo Tu We Th Fr Sa Su\n 1  2  3  4  5  6  7\n 8  9 10 11 12 13 14\n15 16 17 18 19 20 21\n22 23 24 25 26 27 28\n29 30\n'

3.calendar.isleap(): 判断某年是不是闰年。

>>> calendar.isleap(2019)
False

4. calendar.leapdays(): 判断某年是不是闰年。

>>> calendar.leapdays(2000,2019)
5

5.calendar.monthcalendar(): 以嵌套列表的形式返回某年某个月的日历。

>>> calendar.monthcalendar(2019, 4)
[[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14], [15, 16, 17, 18, 19, 20, 21], [22, 23, 24, 25, 26, 27, 28], [29, 30, 0, 0, 0, 0, 0]]

6.calendar.monthrange():
该函数返回两个整数,第一个数为某月第一天为星期几,第二个数为该月有多少天。

>>> calendar.monthrange(2019, 4)
(0, 30)

7.calendar.timegm(): 将一个元组时间变成时间戳。

>>> import time
>>> calendar.timegm(time.localtime())
1555020301

四、random模块

random模块用于生成随机数。
1…random.random():

生成0-1之间的随机数

>>> import random
>>> random.random()
0.657103869811327

2.random.uniform(a,b): 用于生成一个指定范围内的随机符点数,两个参数其中一个是上限,一个是下限。如果a > b,则生成的随机数n: a <= n <= b。如果 a <b, 则 b <= n <= a。

>>> random.uniform(2,5)
3.6732072768961377

>>> random.uniform(5,2)
4.7789053140090445

3 random.randint(a, b): 用于生成一个指定范围内的整数。其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b

>>> random.randint(1,10)
3

4.random.randrange([start], stop[, step]): 从指定范围内,按指定基数递增的集合中 获取一个随机数。

>>> random.randrange(10,20,2)    # 从[10,12,14,16,17,18]中随机娶一个数
16

5. random.choice(sequence):
从序列中获取一个随机元素

>>> random.choice(['a',123,'def',3])
3

6.random.shuffle(x[, random]): 将一个列表中的元素打乱,即将列表内的元素随机排列

>>> random.shuffle([1,2,3,4,5])
>>> a = [1,2,3,4,5]
>>> random.shuffle(a)
>>> a
[5, 2, 3, 4, 1]

7…random.sample(sequence, k): 从指定序列中随机获取指定长度的片断并随机排列。注意:sample函数不会修改原有序列。

>>> a = [1,2,3,4,5,6,7,8,9]
>>> random.sample(a,4)
[3, 2, 4, 7]
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值