1、python3日期和时间
Python 程序能用很多方式处理日期和时间,转换日期格式是一个常见的功能。
Python 提供了一个 time 和 calendar 模块可以用于格式化日期和时间。
时间间隔是以秒为单位的浮点小数。
每个时间戳都以自从1970年1月1日午夜(历元)经过了多长时间来表示。
Python 的 time 模块下有很多函数可以转换常见日期格式。如函数time.time()用于获取当前时间戳
>>> import time >>> print(time.time()) 1508312234.7298932 #时间戳单位最适于做日期运算。但是1970年之前的日期就无法以此表示了。太遥远的日期也不行,UNIX和Windows只支持到2038年。
2、时间元组
很多Python函数用一个元组装起来的9组数字处理时间
字段 | 属性 | 值 |
4位年数 | tm_year | 2017 |
月 | tm_mon | 1到12 |
日 | tm_mday | 1到31 |
小时 | tm_hour | 0到23 |
分钟 | tm_min | 0到59 |
秒 | tm_sec | 0到61(60或61是润秒) |
一周的第几日 | tm_wday | 0到6(0是周一) |
一年的第几日 | tm_yday | 1到366,一年中的第几天 |
夏令时 | tm_isdst | 是否为夏令时,值为1时是夏令时,值为0时不是夏令时,默认为-1 |
#从返回浮点数的时间辍方式向时间元组转换,只要将浮点数传递给如localtime之类的函数 >>> print(time.localtime(time.time())) time.struct_time(tm_year=2017, tm_mon=10, tm_mday=18, tm_hour=15, tm_min=40, tm_sec=59, tm_wday=2, tm_yday=291, tm_isdst=0)
#当前时间为:2017年,10月,18日,15时,40分,59秒,星期三,一年中的291天,不是夏令
3、获取格式化的时间
可以根据需求选取各种格式,但是最简单的获取可读的时间模式的函数是asctime()
>>> import time >>> print(time.asctime(time.localtime(time.time()))) Wed Oct 18 16:03:24 2017 #wed为星期三,oct为october十月的缩写,18日,时间,年
4、格式化日期
可以使用 time 模块的 strftime 方法来格式化日期
python中时间日期格式化符号:
- %y 两位数的年份表示(00-99)
- %Y 四位数的年份表示(000-9999)
- %m 月份(01-12)
- %d 月内中的一天(0-31)
- %H 24小时制小时数(0-23)
- %I 12小时制小时数(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 本地相应的日期表示
- %X 本地相应的时间表示
- %Z 当前时区的名称
- %% %号本身
>>> import time >>> print(time.strftime('%Y',time.localtime())) #获取完整年份 2017 >>> print(time.strftime('%y',time.localtime())) #获取简写年份 17 >>> print(time.strftime('%m',time.localtime())) #获取月 10 >>> print(time.strftime('%d',time.localtime())) #获取日 18 >>> print(time.strftime('%Y-%m-%d',time.localtime())) #获取年-月-日 2017-10-18
>>> print(time.strftime(’%H’,time.localtime())) #获取时,24小时制
16
>>> print(time.strftime(’%l’,time.localtime())) #获取时,12小时制
4
>>> print(time.strftime(’%M’,time.localtime())) #获取分
33
>>> print(time.strftime(’%S’,time.localtime())) #获取秒
31
>>> print(time.strftime(’%H:%M:%S’,time.localtime())) #获取时:分:秒
16:34:28
>>> print(time.strftime(’%a’,time.localtime())) #本地简化星期
Wed
>>> print(time.strftime(’%A’,time.localtime())) #本地完整星期
Wednesday
>>> print(time.strftime(’%b’,time.localtime())) #本地简化月份
Oct
>>> print(time.strftime(’%B’,time.localtime())) #本地完整月份
October
>>> print(time.strftime(’%c’,time.localtime())) #本地日期和时间表示
Wed Oct 18 16:37:46 2017
>>> print(time.strftime(’%j’,time.localtime())) #一年中的第几天
291
>>> print(time.strftime(’%p’,time.localtime())) #P.M等价符
PM
>>> print(time.strftime(’%U’,time.localtime())) #一年中的第几个星期,星期天为星期的开始
42
>>> print(time.strftime(’%w’,time.localtime())) #星期几,星期天为星期的开始
3
>>> print(time.strftime(’%W’,time.localtime())) #一年中的第几个星期,星期一为星期的开始
42
>>> print(time.strftime(’%x’,time.localtime())) #本地日期表示
10/18/17
>>> print(time.strftime(’%X’,time.localtime())) #本地时间表示
17:16:17
>>> print(time.strftime(’%Z’,time.localtime())) #当前时区
CST
>>> print(time.strftime(’%%’,time.localtime())) #输出%本身
%
>>> print(time.strftime(’%Y-%m-%d %H:%M:%S %w-%Z’,time.localtime()))
2017-10-18 17:25:39 3-CST #完整日期,时间,星期,时区
5、获取月日历
Calendar模块有很广泛的方法用来处理年历和月历
>>> import calendar >>> cal=calendar.month(2017,10) >>> print(cal) October 2017 Mo Tu We Th Fr Sa Su 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 31
#calendar.calendar(2017)
#返回一个多行字符串格式的year年年历,3个月一行,间隔距离为c。
每日宽度间隔为w字符。
每行长度为21* W+18+2* C。l是每星期行数。
>>> c = calendar.calendar(2017)
>>> print©
2017
January February March
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 1 2 3 4 5 1 2 3 4 5
2 3 4 5 6 7 8 6 7 8 9 10 11 12 6 7 8 9 10 11 12
9 10 11 12 13 14 15 13 14 15 16 17 18 19 13 14 15 16 17 18 19
16 17 18 19 20 21 22 20 21 22 23 24 25 26 20 21 22 23 24 25 26
23 24 25 26 27 28 29 27 28 27 28 29 30 31
30 31
April May June
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 1 2 3 4 5 6 7 1 2 3 4
3 4 5 6 7 8 9 8 9 10 11 12 13 14 5 6 7 8 9 10 11
10 11 12 13 14 15 16 15 16 17 18 19 20 21 12 13 14 15 16 17 18
17 18 19 20 21 22 23 22 23 24 25 26 27 28 19 20 21 22 23 24 25
24 25 26 27 28 29 30 29 30 31 26 27 28 29 30
July August September
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 1 2 3 4 5 6 1 2 3
3 4 5 6 7 8 9 7 8 9 10 11 12 13 4 5 6 7 8 9 10
10 11 12 13 14 15 16 14 15 16 17 18 19 20 11 12 13 14 15 16 17
17 18 19 20 21 22 23 21 22 23 24 25 26 27 18 19 20 21 22 23 24
24 25 26 27 28 29 30 28 29 30 31 25 26 27 28 29 30
31
October November December
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 1 2 3 4 5 1 2 3
2 3 4 5 6 7 8 6 7 8 9 10 11 12 4 5 6 7 8 9 10
9 10 11 12 13 14 15 13 14 15 16 17 18 19 11 12 13 14 15 16 17
16 17 18 19 20 21 22 20 21 22 23 24 25 26 18 19 20 21 22 23 24
23 24 25 26 27 28 29 27 28 29 30 25 26 27 28 29 30 31
30 31
#calendar.firstweekday返回当前每周起始日期的设置。默认情况下,首次载入calendar模块时返回0,即星期一。 >>> calendar.firstweekday() 0 #calendar.setfirstweekday设置每周的起始日期码。0(星期一)到6(星期日)。 >>> calendar.setfirstweekday(1) >>> calendar.firstweekday() 1
calendar.isleap是闰年返回True,否则为false。
>>> calendar.isleap(2017)
False
>>> print(calendar.isleap(2020))
True
#calendar.leapdays返回在两年之间的闰年总数,但不包括末年
>>> print(calendar.leapdays(2016,2020))
1
>>> print(calendar.leapdays(2016,2021))
2
#calendar.monthcalendar返回一个整数的单层嵌套列表,每个子列表装载代表一个星期,月外的日期设为0
>>> print(calendar.monthcalendar(2017,10))
[[0, 0, 0, 0, 0, 0, 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, 31, 0, 0, 0, 0, 0]]
>>> print(calendar.month(2017,10))
October 2017
Mo Tu We Th Fr Sa Su
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 31
#calendar.monthrange返回两个整数,第一个为该月的首日的星期(0-6),第二个为该月的总天数
>>> print(calendar.monthrange(2017,10))
(6, 31)
#calendar.timegm接受一个时间元组形式struct_time,返回该时刻的时间辍(1970纪元后经过的浮点秒数)
>>> print(calendar.timegm((2017,10,19,14,50,0,0,0,0)))
1508424600
>>> print(calendar.timegm((2017,10,19,14,50,50,0,0,0)))
1508424650
>>> print(time.localtime(time.time()))
time.struct_time(tm_year=2017, tm_mon=10, tm_mday=19, tm_hour=14, tm_min=49, tm_sec=44, tm_wday=3, tm_yday=292, tm_isdst=0)
#calendar.weekday返回给定日期的星期码。0(星期一)到6(星期日)。月份为 1(一月) 到 12(12月)。
>>> print(calendar.weekday(2017,10,19))
3
>>> print(calendar.weekday(2017,10,20))
4
6、Time模块
Time 模块包含了以下内置函数,既有时间处理相的,也有转换时间格式的:
#time.altzone #返回格林威治西部的夏令时地区的偏移秒数。如果该地区在格林威治东部会返回负值(如西欧,包括英国)。对夏令时启用地区才能使用。 >>> import time >>> print(time.altzone) -28800
#time.asctime([tupletime])
#接受时间元组并返回一个可读的形式为"Thu Oct 19 15:07:31 2017"(2017年10月19日 周四15时07分31秒)的24个字符的字符串。
>>> print(time.asctime(time.localtime()))
Thu Oct 19 15:07:31 2017
#time.clock()
#用以浮点数计算的秒数返回当前的CPU时间。用来衡量不同程序的耗时,比time.time()更有用。
>>> import time
>>> def procedure():
… time.sleep(2.5)
…
>>> t0 = time.clock()
>>> procedure()
>>> print(time.clock() - t0)
0.010000000000000009
>>> print(time.clock() - t0)
0.020000000000000004
#time.ctime()作用相当于asctime(localtime(secs)),未给参数相当于asctime()
>>> import time
>>> print(time.ctime())
Thu Oct 19 19:24:24 2017
>>> print(time.asctime(time.localtime()))
Fri Oct 20 11:10:00 2017
>>> print(time.asctime())
Fri Oct 20 11:10:19 2017
#time.gmtime()以元组方式返回格林威治时间
>>> print(time.gmtime())
time.struct_time(tm_year=2017, tm_mon=10, tm_mday=20, tm_hour=3, tm_min=27, tm_sec=30, tm_wday=4, tm_yday=293, tm_isdst=0)
#time.localtime()以元组方式返回本地当前时间
>>> print(time.localtime())
time.struct_time(tm_year=2017, tm_mon=10, tm_mday=20, tm_hour=11, tm_min=30, tm_sec=33, tm_wday=4, tm_yday=293, tm_isdst=0)
#time.mktime()将元组时间转换为时间戳
>>> x = time.localtime()
>>> x
time.struct_time(tm_year=2017, tm_mon=10, tm_mday=20, tm_hour=11, tm_min=32, tm_sec=8, tm_wday=4, tm_yday=293, tm_isdst=0)
>>> time.mktime(x)
1508470328.0
#time.strftime(fmt[,tupletime])
#接收以时间元组,并返回以可读字符串表示的当地时间,格式由fmt决定。
>>> print(time.strftime(’%Y-%m-%d %H:%M:%S’,time.localtime()))
2017-10-20 17:29:08
#time.strptime() #根据fmt的格式把一个时间字符串解析为时间元组。 >>> print(time.strptime('23 Oct 2017','%d %b %Y')) time.struct_time(tm_year=2017, tm_mon=10, tm_mday=23, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=296, tm_isdst=-1) >>> print(time.strptime('23 Oct 2017 14 03 00','%d %b %Y %H %M %S')) time.struct_time(tm_year=2017, tm_mon=10, tm_mday=23, tm_hour=14, tm_min=3, tm_sec=0, tm_wday=0, tm_yday=296, tm_isdst=-1)
#time.time
#返回当前时间的时间戳(1970年经过的秒数)
>>> print(time.time())
1508739061.9443805
#time.timezone
#是当地时区距离格林威治偏移的秒数
>>> print(time.timezone)
-28800
#time.tzname
#输出一个包含一个不包含夏令时的本地时区名称
>>> print(time.tzname)
(‘CST’, ‘CST’)
>>> from datetime import datetime >>> print(datetime.now()) 2017-10-23 14:30:48.971017
转载自Fate0729
datetime:
import datetime
datetime.datetime.now() #获取当前时间
Out[33]: datetime.datetime(2017, 7, 3, 15, 57, 26, 184085)
datetime.datetime.now()+datetime.timedelta(3) #当前时间+3天
Out[35]: datetime.datetime(2017, 7, 6, 15, 58, 47, 949762)
datetime.datetime.now()+datetime.timedelta(hours=3) #当前时间+3小时
Out[36]: datetime.datetime(2017, 7, 3, 18, 59, 15, 221322)
datetime.datetime.now()+datetime.timedelta(minutes=3) #当前时间+3分钟
Out[37]: datetime.datetime(2017, 7, 3, 16, 2, 45, 578058)
我们先看如何获取当前日期和时间:
>>> from datetime import datetime
>>> now = datetime.now() # 获取当前datetime
>>> print(now)
2015-05-18 16:28:07.198690
>>> print(type(now))
<class 'datetime.datetime'>
注意到datetime
是模块,datetime
模块还包含一个datetime
类,通过from datetime import datetime
导入的才是datetime
这个类。
如果仅导入import datetime
,则必须引用全名datetime.datetime
。
datetime.now()
返回当前日期和时间,其类型是datetime
。
datetime转换为str
如果已经有了datetime对象,要把它格式化为字符串显示给用户,就需要转换为str,转换方法是通过strftime()
实现的,同样需要一个日期和时间的格式化字符串:
>>> from datetime import datetime
>>> now = datetime.now()
>>> print(now.strftime('%a, %b %d %H:%M'))
Mon, May 05 16:28
datetime加减
对日期和时间进行加减实际上就是把datetime往后或往前计算,得到新的datetime。加减可以直接用+
和-
运算符,不过需要导入timedelta
这个类:
>>> from datetime import datetime, timedelta
>>> now = datetime.now()
>>> now
datetime.datetime(2015, 5, 18, 16, 57, 3, 540997)
>>> now + timedelta(hours=10)
datetime.datetime(2015, 5, 19, 2, 57, 3, 540997)
>>> now - timedelta(days=1)
datetime.datetime(2015, 5, 17, 16, 57, 3, 540997)
>>> now + timedelta(days=2, hours=12)
datetime.datetime(2015, 5, 21, 4, 57, 3, 540997)
可见,使用timedelta
你可以很容易地算出前几天和后几天的时刻。
转载自Zoe233
random
random是内建(built-in)函数,作用是产生随机数
导入模块:
import random
接着就可以调用random模块下的函数了使用 dir(random)可以查看random模块下有哪些函数,结果如下:
-
>>> dir(random)
-
[
'BPF',
'LOG4',
'NV_MAGICCONST',
'RECIP_BPF',
'Random',
'SG_MAGICCONST',
'SystemRandom',
'TWOPI',
'_BuiltinMethodType',
'_MethodType',
'_Sequence
-
',
'_Set',
'__all__',
'__builtins__',
'__cached__',
'__doc__',
'__file__',
'__loader__',
'__name__',
'__package__',
'__spec__',
'_acos',
'_bisect
-
',
'_ceil',
'_cos',
'_e',
'_exp',
'_inst',
'_itertools',
'_log',
'_pi',
'_random',
'_sha512',
'_sin',
'_sqrt',
'_test',
'_test_generator',
'_urandom'
-
,
'_warn',
'betavariate',
'choice',
'choices',
'expovariate',
'gammavariate',
'gauss',
'getrandbits',
'getstate',
'lognormvariate',
'normalvariate',
-
'paretovariate',
'randint',
'random',
'randrange',
'sample',
'seed',
'setstate',
'shuffle',
'triangular',
'uniform',
'vonmisesvariate',
'weibullvaria
-
te']
最常用的函数有如下:
random.randint
random.randint(1,10)
语句的含义是产生1至10(
包含1与10)的一个随机数(
整数int型)。(参数为整数不可为浮点数否则会报错)
random.randint(20, 10) #该语句是错误的。下限必须小于或等于上限。
random.random
random.random()
生成一个0到1之间的随机浮点数,包括0但不包括1,也就是[0.0, 1.0)。
random.uniform
random.uniform(a, b)
生成a、b之间的随机浮点数。不过与randint不同的是,a、b可以不是整数,也不用考虑大小。
即
random.uniform(3.65,10.56)#可以这样
random.uniform(10.56, 3.65)#也可以这样
random.choice
random.choice(seq)
从序列中随机选取一个元素。seq需要是一个序列,比如list、元组、字符串。
-
random.choice([
1,
2,
3,
5,
8,
13])
#list
-
-
random.choice(
'hello')
#字符串
-
-
random.choice([
'hello',
'world'])
#字符串组成的list
-
-
random.choice((
1,
2,
3))
#元组
都是可行的用法。
random.randrange
random.randrange(start, stop, step)
生成一个从start到stop(不包括stop),间隔为step的一个随机整数。start、stop、step都要为整数,且start<stop。
random.sample
random.sample(p, k)
从p序列中,随机获取k个元素,生成一个新序列。
sample不改变原来序列。
这个模块很 666,还支持三角、β分布、指数分布、伽马分布、高斯分布等等非常专业的随机算法。
random.shuffle
random.shuffle(x)
把序列x中的元素顺序打乱。
shuffle直接改变原有的序列。如:
-
import random
-
a=[
1,
2,
3,
4,
5,
6]
-
random.shuffle(a)
-
print(a)
结果如下:
[5, 1, 3, 6, 4, 2]
新手在使用此函数时可能会出现一些错误,如下:
-
import random
-
a=[
1,
2,
3,
4,
5,
6]
-
print(random.shuffle(a))
使用此方法会出现
None结果,原因是random.shuffle() 是用来打乱列表元素的,没有返回值,所以不能用print(random.shuffle(a))来输出打印打乱后的序列
转载自Don-ML