【Python拾遗】Python 日期和时间模块time、datetime、calendar

Python的日期和时间模块常用的有三个,分别是:time、datetime、calendar,下面分别来介绍一下。

一、time模块

time模块提供了一些用于管理时间和日期的C库函数,由于它绑定到底层C实现,因此一些细节会基于具体的平台。

1、获取当前时间

a)time()

time模块的核心函数time(),它返回纪元开始的秒数,返回值为浮点数,具体精度依赖于平台。

>>> import time
>>> time.time()
1460599046.85416

b)ctime()

浮点数一般用于存储和比较日期,但是对人类不友好,要记录和打印时间,可以使用ctime()。

>>> import time
>>> time.ctime()
'Thu Apr 14 10:03:58 2016'
>>> later = time.time()+5
>>> time.ctime(later)
'Thu Apr 14 10:05:57 2016'

2、解析和格式化时间

time模块提供了两个函数 strptime() 和 strftime(),可以在time.struct_time(在第三点中有介绍)和时间值字符串之间转换。

a)strptime()   

用于将字符串时间转换成struct_time格式:

>>> now=time.ctime()
>>> time.strptime(now)
time.struct_time(tm_year=2016, tm_mon=4, tm_mday=14, tm_hour=10, tm_min=48, tm_sec=40,
 tm_wday=3, tm_yday=105, tm_isdst=-1)

b)strftime()   

用于时间的格式化输出:

>>> from time import gmtime, strftime
>>> strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
'Thu, 28 Jun 2001 14:17:15 +0000'

"""
注: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 当前时区的名称
    %% %号本身
"""

c)mktime()   

用于将struct_time转换成时间的浮点数表示:

>>> from time import mktime, gmtime
>>> mktime(gmtime())
1460573789.0

3、time.struct_time类

struct_time类是time模块定义的用来维护时间和日期的类,存储时间的各个部分,以便访问。time.gmtime()和time.localtime()的返回的值就是struct_time类型对象。localtime()用于获取当前时区的当前时间,gmtime()用于获取UTC时间,UTC时间实际就是格林尼治时间,它与中国时间的时差为八个小时。

import time
def show_struct(t):
    # 这边可以直接用t.()访问时间元素
    print("tm_year:", t.tm_year)
    print("tm_mon:", t.tm_mon)
    print("tm_mday:", t.tm_mday)
    print("tm_hour:", t.tm_hour)
    print("tm_min:", t.tm_min)
    print("tm_sec:", t.tm_sec)
    print("tm_wday:", t.tm_wday)
    print("tm_yday:", t.tm_yday)
show_struct(time.gmtime())
show_struct(time.localtime())

注:struct_time对象的属性

序号

属性

0

tm_year

2008

1

tm_mon

1 到 12

2

tm_mday

1 到 31

3

tm_hour

0 到 23

4

tm_min

0 到 59

5

tm_sec

0 到 61 (60或61 是闰秒)

6

tm_wday

0到6 (0是周一)

7

tm_yday

一年中的第几天,1 到 366

8

tm_isdst

是否为夏令时,值有:1(夏令时)、0(不是夏令时)、-1(未知),默认 -1

4、处理时区

a)获取时间差

>>> import time
>>> time.timezone/3600
-8

b)设置时区

ZONES = ["GMT", "EUROPE/Amsterdam']
for zone in ZONES:
    os.environ["TZ"] = zone
    time.tzset()

5、程序的实际运行时间

process_time()和perf_counter()返回处理器时钟时间,它的返回值一般用于性能测试与基准测试。因此它们反映了程序的实际运行时间。

>>> import time
>>> time.process_time()
0.07

6、sleep()

sleep函数用于将当前线程交出,要求它等待系统将其再次唤醒,如果写程序只有一个线程,这实际上就会阻塞进程,什么也不做。

# 执行以下代码,将等待5秒钟之后再输出信息。
import time
def fucn():
    time.sleep(5)
    print("hello, world")

 

二、datetime模块

python中的datetime模块提供了操作日期和时间功能, 该模块提供了五种核心对象:datetime(时间日期类型), date(日期类型), time(时间类型), tzinfo(时区类型), timedelta(时间差类型)。分别如下:

1、datetime 对象

datetime对象可以用来表示精确的日期和时间,其实例化方法如下

>>> from datetime import datetime
>>> birthday = datetime(year=1993, month=10, day=20)
>>> birthday
datetime.datetime(1993, 10, 20, 0, 0)
>>> birthday.month
10
>>> now = datetime.now() # 返回当前时间
>>> now
datetime.datetime(2016, 12, 17, 20, 3, 25, 898000)

在实例化datetime对象时,year, month, day是必填项,hour, minute, second, microsecond(微秒), tzinfo(时区)是可选项。

2、date 对象

date对象和datetime对象的区别在于,date对象只能表示日期,不能表示时间(即其精确度为天)。date实例化时须要且仅须要三个参数:year, month, day。date对象是没有时区(tzinfo)属性的。

>>> from datetime import date
>>> birthday = date(year=2016, month=12, day=17)
>>> birthday
datime.date(2016, 12, 17)
>>> birthday.year
2016

3、time对象

和date对象相反,time对象只能用来表示时间,而不能用来表示日期。time对象所表示的时间可以精确到微秒,而且可以具有时区(tzinfo)属性。

>>> from datetime import time
>>> now_time = time(hours=20, minute=30, second=10) 
# hours, minute, second,microsecond, tzinfo都是可选参数
>>> now_time
datetime.time(20, 30, 10)
>>> now_time.hours
20

4、timedelta对象

timedelta对象表示一个时间段,timedelta对象可以通过手动实例化得到,也可以通过上述三个对象(datetime, date, time)相减得到。

>>> from datetime import datetime, timedleta
>>> now = datetime.now()
>>> last = datetime(year=2016, month=3, day=10, hour=8)
>>> delta = now - last
>>> delta
datetime.timedelta(282, 47010, 328000)
>>> last + delta == now
True

手动实例化timedelta时,可以传入的参数有:days, seconds, microseconds, milliseconds, minutes, hours, weeks。

 

5、tzinfo对象

讲解tzinfo(时区)对象前,先了解两个概念:

        a)UTC时间: 协调世界时。和GMT(格林尼治平均时间)是一个东西,只不过UTC是通过原子钟测量出来,GMT是通过天文观测出来的,所以UTC比GMT精度更高,因此现在世界上不同时区的时间都是以UTC时间为基准,如:北京时间=UTC时间+8小时

        b)DST:夏时令(daylight saving time),因为夏天天亮的早,所以有的国家就在一年的某些时段把时间人为的调快一小时,使人们早睡,减少照明亮,充分利用光照资源,从而节约能源。我国也实行过,不过后来废止了。

tzinfo对象是用来表示该时区相对UTC时间差值,和该地区是否执行夏时令的对象。datetime模块所提供的的tzinfo对象是一个抽象基类,也就是说我们不应该直接实例化此对象, 而应该以此类为基类,定义出子类,然后再实例化以供使用。在子类化的时候,需要自定义很多方法,非常繁琐。还好python提供了一个pytz的库,里面自带了适合各个国家和时区的tzinfo对象,我们可以直接使用。

在python中,我们把tzinfo为空的datetime对象称为是aware(觉醒)的,把tzinfo不为空的datetime对象称为naive(幼稚)的。使用datetime模块时,除非手动指定tzinfo属性,否则,创建出来的datatime对象tzinfo属性都默认为空。

aware 对象具有关于应用规则和时间调整的充分的信息,例如时区和夏令时信息,来定位相对其他aware 对象的位置。aware对象用于表示时间的一个特定的时刻,它是明确无二的。

naive 对象没有充分的信息来明确地相对其他日期/时间定位它自己。一个 naive 对象表示的是世界协调时(UTC)、本地时间还是其它时区的时间完全取决于程序,就像一个特定的数字表示的是米、英里还是质量一样。

>>> from datetime import datetime
>>> import pytz
>>> utc_tz = pytz.timezone('UTC')
>>> china_tz = pytz.timezone('China/Shanghai')
>>> local_naive = datetime.now()
>>> local_naive
datetime.datetime(2016, 12, 18, 8, 8, 14000)
>>> local_aware = localmoment_aware.replace(china_tz)
datetime.datetime(2016, 12, 18, 8, 8, 14000, tzinfo=<DstTzInfo 'Asia/Shanghai' LMT+8>)
>>> utc_aware = local_aware.astimezone(utc_tz)
>>> utc_aware
datetime.datetime(2016, 12, 18, 0, 8, 14000, tzinfo=<UTC>
>>> utc_aware - local_aware  #虽然时区不同但是表示的同一个时间点
datetime.timedelta(0)

注意,aware类型的datetime对象,只能和aware类型的datetime对象进行运算(相减,大小比较等)。navie类型的datetime对象,只能和naive类型的datetime对象进行运算(相减,大小比较等)。aware类型和naive类型之间运算会报错:

>>> local_naive - local_aware
TypeError:can't subtract offset-naive and offset-aware datetime

三、calendar模块

calendar是与日历相关的模块,calendar模块文件里定义了很多类型,主要有Calendar,TextCalendar以及HTMLCalendar类型。其中,Calendar是TextCalendar与HTMLCalendar的基类。该模块文件还对外提供了很多方法,例如:calendar,month,prcal,prmonth之类的方法...

1、calendar()获取指定年份的日历字符串

>>> import calendar
>>> calen=calendar.calendar(2020)
>>> print(calen)
"""
                                  2020

      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  2  3  4  5                      1  2                         1
 6  7  8  9 10 11 12       3  4  5  6  7  8  9       2  3  4  5  6  7  8
13 14 15 16 17 18 19      10 11 12 13 14 15 16       9 10 11 12 13 14 15
20 21 22 23 24 25 26      17 18 19 20 21 22 23      16 17 18 19 20 21 22
                                                    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  3  4  5                   1  2  3       1  2  3  4  5  6  7
 6  7  8  9 10 11 12       4  5  6  7  8  9 10       8  9 10 11 12 13 14
13 14 15 16 17 18 19      11 12 13 14 15 16 17      15 16 17 18 19 20 21
20 21 22 23 24 25 26      18 19 20 21 22 23 24      22 23 24 25 26 27 28
27 28 29 30               25 26 27 28 29 30 31      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  3  4  5                      1  2          1  2  3  4  5  6
 6  7  8  9 10 11 12       3  4  5  6  7  8  9       7  8  9 10 11 12 13
13 14 15 16 17 18 19      10 11 12 13 14 15 16      14 15 16 17 18 19 20
20 21 22 23 24 25 26      17 18 19 20 21 22 23      21 22 23 24 25 26 27
27 28 29 30 31            24 25 26 27 28 29 30      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  2  3  4                         1          1  2  3  4  5  6
 5  6  7  8  9 10 11       2  3  4  5  6  7  8       7  8  9 10 11 12 13
12 13 14 15 16 17 18       9 10 11 12 13 14 15      14 15 16 17 18 19 20
19 20 21 22 23 24 25      16 17 18 19 20 21 22      21 22 23 24 25 26 27
26 27 28 29 30 31         23 24 25 26 27 28 29      28 29 30 31
                          30
"""

2、month()获取指定月份的日历字符串

>>> import calendar
>>> calen=calendar.month(2020,6)
>>> print(calen)
"""
     June 2020
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
"""

3、isleap()检测年份是否是润年

>>> import calendar
>>> calen1=calendar.isleap(2000)
>>> calen2=calendar.isleap(1900)
>>> print(calen1)
True
>>> print(calen2)
False

4、leapdays()检测指定年限内润年的数量

>>> import calendar
>>> calen1=calendar.leapdays(1949,2020)
>>> print(calen1)
17

5、monthrange() 获取指定月份的信息

>>> import calendar
>>> calen1=calendar.monthrange(2020,6)
>>> print(calen1)
(0, 30)

6、weekday ()根据指定的年月日计算星期几

>>> import calendar
>>> calen1=calendar.weekday(2020,6,13)
>>> print(calen1)
5

7、timegm() 将时间元组转化为时间戳

>>> import calendar
>>> tps = (2020,6,13,22,0,0,0,0)
>>> result = calendar.timegm(tps)
>>> print(result)
1592085600

还有其他函数:

 

参考:

1、https://www.jianshu.com/p/da0ef08c9ea7   作者:nummy

2、https://www.jianshu.com/p/1957c4cab0a3   作者:给我二两面

3、https://www.jianshu.com/p/d2a7204a2a04   作者:我爱学python

猜你喜欢

转载自blog.csdn.net/BobYuan888/article/details/106737773