python:日期与时间之datetime模块

datetime模块:

1、datetime是date与time的结合体,包括date和time的所有信息

2、datetime模块定义了两个常量:datetime.MINYEAR和datetime.MAXYEAR,分别表示datetime所能表示的最 小、最大年份。其中,MINYEAR = 1,MAXYEAR = 9999。(对于偶等玩家,这个范围已经足够用矣~~)

datetime模块定义了下面这几个类:

1、datetime.date:表示日期的类。常用的属性有year, month, day

2、datetime.time:表示时间的类。常用的属性有hour, minute, second, microsecond

3、datetime.datetime:表示日期时间。

4、datetime.timedelta:表示时间间隔,即两个时间点之间的长度。

5、datetime.tzinfo:与时区有关的相关信息。(这里不详细充分讨论该类,感兴趣的童鞋可以参考python手册)
 
注 :datetime.datetime类的应用最为普遍且上面这些类型的对象都是不可变(immutable)的。

datetime.datetime类中有如下方法:

today():

today()方法的语法如下:

datetime.datetime.today()

1、此语法中datetime.datetime指的是datetime模块中的datetime类
2、返回值:返回一个表示当前本地时间的datetime对象(即可以将返回值赋值给一个变量)

例1:

import datetime

print("当前时间为:",datetime.datetime.today())

#上面函数的输出结果为:当前时间为: 2018-08-19 18:58:07.417332

例1_1:

from datetime import datetime

print("当前时间为:",datetime.today())

#上面函数的输出结果为:当前时间为: 2018-08-19 18:58:07.417332


now([tz]):

now()方法的语法如下:

datetime.datetime.now([tz])

1、此语法中datetime.datetime指的是datetime模块中的datetime类
2、如果提供参数tz,就获取tz参数所指时区的本地时间(now是本地时间,可以认为是你电脑现在的时间)
3、返回值:返回当前指定的本地时间

例2:

from datetime import datetime

print("当前时间为:",datetime.now())

#上面函数的输出结果为:当前时间为: 2018-08-19 19:07:33.719778


utcnow():

utcnow()方法的语法如下:

datetime.datetime.utcnow()

1、此语法中datetime.datetime指的是datetime模块中的datetime类
2、返回值:返回一个当前utc时间的datetime对象

例3:

from datetime import datetime

print("当前时间为:",datetime.utcnow())
print("当前时间为:",datetime.now())

"""
上面函数的输出结果为:
当前时间为: 2018-08-19 11:12:52.725881
当前时间为: 2018-08-19 19:12:52.725881
"""

 

fromtimestamp(timestamp[,tz]):

fromtimestamp(timestamp[,tz])方法的语法如下:

datetime.datetime.fromtimestamp(timestamp[,tz]

1、此语法中datetime.datetime指的是datetime模块中的datetime类
2、参数tz表示指定的时区信息,参数timestamp表示需要转换的时间戳
3、返回值:返回一个datetime对象,将一个时间戳形式的时间转换为可读形式

例4:

from datetime import datetime
import time

Time = time.time()
print("当前时间为:",datetime.fromtimestamp(Time))

#上面函数的输出结果为:当前时间为: 2018-08-19 19:23:57.303277

strptime(date_string,format):将格式化字符串转换为date对象

strptime()方法的语法如下:

datetime.datetime.strptime(date_string,format)

1、此语法中datetime.datetime指的是datetime模块中的datetime类
2、参数date_string指日期字符串,format为格式方式
3、返回值:返回一个datetime对象

例5:

from datetime import datetime

try:
    Time = datetime.now()

    print("当前时间为:",Time.strptime(str(Time),"%Y-%m-%d %H:%M:%S.%f")) #必须格式化秒

except:       #except ValueError:
    pass

#捕捉到任意异常后,不做任何处理,忽略错误,


#上面函数的输出结果为:当前时间为: 2018-08-19 19:46:46.814034

strftime(format):将格式化字符串转换为date对象

strftime()方法的语法如下:

datetime.datetime.strftime(format)

1、此语法中datetime.datetime指的是datetime模块中的datetime类
2、参数format为格式化方式
3、返回值:返回一个datetime对象

例6:

from datetime import datetime


Time = datetime.now()

print("当前时间为:",Time.strftime("%Y-%m-%d %H:%M:%S"))    #可以不格式化秒
print("当前时间为:", Time.strftime("%Y-%m-%d %H:%M:%S.%f"))

"""
上面函数的输出结果为:
当前时间为: 2018-08-19 19:53:22
当前时间为: 2018-08-19 19:53:22.028378
"""


注:以上方法为datetime.datetime类的类方法或属性,以下为datetime.datetime类的对象方法或属性

datetime类对象方法和属性

对象方法 描述
dt.year, dt.month, dt.day 年、月、日
dt.hour, dt.minute, dt.second 时、分、秒
dt.microsecond, dt.tzinfo 微秒、时区信息
dt.date() 获取datetime对象对应的date对象
dt.time() 获取datetime对象对应的time对象, tzinfo 为None
dt.timetuple() 返回datetime对象对应的tuple(不包括tzinfo)
dt.timetz() 获取datetime对象对应的time对象,tzinfo与datetime对象的tzinfo相同
dt.utctimetuple() 返回datetime对象对应的utc时间的tuple(不包括tzinfo)
dt.toordinal() 同date对象
dt.weekday() 同date对象
dt.isocalendar() 同date独享
dt.isoformat([sep])     返回一个‘%Y-%m-%d
dt.ctime()     等价于time模块的time.ctime(time.mktime(d.timetuple()))
dt.strftime(format) 返回指定格式的时间字符串
dt.replace([year, month, day, hour,minute,second, microsecond, tzinfo) 生成并返回一个新的datetime对象

例:

import datetime,time

today = datetime.datetime.now()

print(today.year)
print(today.hour)
print(today.date())
print(today.time())


'''
上面函数的输出结果为:
2018
17
2018-08-25
17:01:33.202716
'''

 

datetime.date类

datetime.date类的定义:

class datetime.date(year, month, day)

year, month 和 day都是是必须参数,各参数的取值范围为:

参数名称 取值范围
year [MINYEAR, MAXYEAR]
month [1, 12]
day [1, 指定年份的月份中的天数]

 

datetime.date类的类方法和属性

类方法/属性名称 描述
date.max date对象所能表示的最大日期:9999-12-31
date.min date对象所能表示的最小日志:00001-01-01
date.resoluation date对象表示的日期的最小单位:天
date.today() 返回一个表示当前本地日期的date对象
date.fromtimestamp(timestamp) 根据跟定的时间戳,返回一个date对象

例1:

import datetime,time

Time = time.time()   #返回当前时间的世时间戳
Today = datetime.date.today()  #返回当前日期

print(datetime.date.fromtimestamp(Time))
print(Today)

"""
上面代码的输出结果为:
2018-08-25
2018-08-25
"""


datetime.date类的对象方法和属性

对象方法/属性名称 描述(d表示实例对象)
d.year
d.month
d.day
d.toordinal() 返回日期是是自 0001-01-01 开始的第多少天
d.weekday()     返回日期是星期几,[0, 6],0表示星期一
d.isoweekday() 返回日期是星期几,[1, 7], 1表示星期一
d.isocalendar() 返回一个元组,格式为:(year, weekday, isoweekday)

例2:

import datetime,time

Today = datetime.date.today()  #返回当前日期

print(Today.year,Today.month,Today.day)

#上面代码的输出结果为:2018 8 25

例2_2:

import datetime,time

Today = datetime.date.today()  #返回当前日期
new_day = Today.replace(2019,1,1)
new_Day = datetime.date.today().replace(2019,2,2)   #写法不同

print(Today,new_day,new_Day)

#上面代码的输出结果为:2018-08-25 2019-01-01 2019-02-02

例2_3:

import datetime,time

Today = datetime.date.today()  #返回当前日期
new_day = Today.replace(2019,1,1)

print(datetime.date.timetuple(new_day)) #注意下这种写法与下面的写法
print(Today.toordinal())
print(Today.isoformat())
print(Today.strftime("%Y/%m/%d"))


"""
上面代码的输出结果为:
time.struct_time(tm_year=2019, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=1, tm_isdst=-1)
736931
2018-08-25
2018/08/25
"""

datetime.time类

time类的定义

class datetime.time(hour, [minute[, second, [microsecond[, tzinfo]]]])

hour为必须参数,其他为可选参数。各参数的取值范围为:

参数名称 取值范围
hour [0, 23]
minute [0, 59]
second     [0, 59]
microsecond [0, 1000000]
tzinfo tzinfo的子类对象,如timezone类的实例

datetime.time类的类方法和属性

类方法/属性名称 描述
time.max time类所能表示的最大时间:time(23, 59, 59, 999999)
time.min time类所能表示的最小时间:time(0, 0, 0, 0)
time.resolution 时间的最小单位,即两个不同时间的最小差值:1微秒

datetime.time类的对象方法和属性

对象方法/属性名称  描述
t.hour
t.minute   分
t.second  秒
t.microsecond  微秒
t.isoformat() 返回一个‘HH:MM:SS.%f’格式的时间字符串
t.strftime() 返回指定格式的时间字符串,与time模块的strftime(format, struct_time)功能相同
>>> from datetime import time
>>>
>>> time.max
datetime.time(23, 59, 59, 999999)
>>> time.min
datetime.time(0, 0)
>>> time.resolution
datetime.timedelta(0, 0, 1)
>>>
>>> t = time(20, 5, 40, 8888)
>>> t.hour
20
>>> t.minute
5
>>> t.second
40
>>> t.microsecond
8888
>>> t.tzinfo
>>>
>>> t.replace(21)
datetime.time(21, 5, 40, 8888)
>>> t.isoformat()
'20:05:40.008888'
>>> t.strftime('%H%M%S')
'200540'
>>> t.strftime('%H%M%S.%f')
'200540.008888'

datetime.timedelta类

timedelta对象表示连个不同时间之间的差值。如果使用time模块对时间进行算术运行只能将字符串格式的时间 和 struct_time格式的时间对象 先转换为时间戳格式,然后对该时间戳加上或减去n秒,最后再转换回struct_time格式或字符串格式,这显然很不方便。而datetime模块提供的timedelta类可以让我们很方面的对datetime.date, datetime.time和datetime.datetime对象做算术运算,且两个时间之间的差值单位也更加容易控制。这个差值的单位可以是:天、秒、微秒、毫秒、分钟、小时、周。

datetime.timedelta类的定义

class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, hours=0, weeks=0)

所有参数都是默认参数,因此都是可选参数参数的值可以是整数或浮点数,也可以是正数或负数。内部值存储days、seconds 和 microseconds,其他所有参数都将被转换成这3个单位:

1毫秒转换为1000微秒

1分钟转换为60秒
1小时转换为3600秒
1周转换为7天

然后对这3个值进行标准化,使得它们的表示是唯一的:

microseconds [0, 999999]
seconds [0, 86399]
days [-999999999, 999999999]


datetime.timedelta类的类属性

类属性名称   描述
timedelta.min timedelta(-999999999)
timedelta.max timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999)
timedelta.resolution  timedelta(microseconds=1)


datetime.timedelta类的实例方法和属性

实例方法/属性名称  描述
td.days  天 [-999999999, 999999999]
td.seconds  秒 [0, 86399]
td.microseconds 微秒 [0, 999999]
td.total_seconds()  时间差中包含的总秒数,等价于: td / timedelta(seconds=1)
datetime.datetime.now()   返回当前本地时间(datetime.datetime对象实例)
datetime.datetime.fromtimestamp(timestamp)   返回指定时间戳对应的时间(datetime.datetime对象实例)
datetime.timedelta()     返回一个时间间隔对象,可以直接与datetime.datetime对象做加减操作

例1:

import datetime

print(datetime.timedelta(365).total_seconds())  #一年中共有多少秒

today = datetime.datetime.now()
print(today)

three_day_later = today + datetime.timedelta(3)   #3天后
print(three_day_later)

three_day_befor = today - datetime.timedelta(days = 3)   #3天前
#three_day_befor = today + datetime.timedelta(-3)
print(three_day_befor)

three_hours_later = today + datetime.timedelta(hours=3)   #3小时后
print(three_hours_later)

new_day = today + datetime.timedelta(days=1,milliseconds=2,seconds=30)   #1天2分钟30秒后
print(new_day)


"""
上面代码的输出结果为:
31536000.0
2018-08-25 11:57:48.249663
2018-08-28 11:57:48.249663
2018-08-22 11:57:48.249663
2018-08-25 14:57:48.249663
2018-08-26 11:58:18.251663
"""

例2:

import datetime,time

today = datetime.datetime.now()
new_day = datetime.date.today().replace(2019,1,1)
New_day = new_day + datetime.timedelta(1)

print(today,new_day,New_day)
print(New_day > new_day)      #对日期进行操作时,要防止日期超出它所能表示的范围。

"""
上面代码的输出结果为:
2018-08-25 12:12:19.047986 2019-01-01 2019-01-02
True
"""

拓展:计算两个时间的时间差

其本上常用的类有:datetime和timedelta两个。它们之间可以相互加减。每个类都有一些方法和属性可以查看具体的值,如datetime可以查看:天数(day),小时数(hour),星期几(weekday())等;timedelta可以查看:天数(days),秒数(seconds)等。

from datetime import datetime,timedelta

future = datetime.strptime("2019-02-01 08:00:00","%Y-%m-%d %H:%M:%S")
now = datetime.now()

TimeEquation = future - now      #计算时间差
#print(TimeEquation)              #145 days, 20:50:32.599774

hours = TimeEquation.seconds/60/60
minutes = (TimeEquation.seconds - hours*60*60)/60
seconds = TimeEquation.seconds - hours*60*60 - minutes * 60

print("今天是:",now.strftime("%Y-%m-%d %H:%M:%S"))
print("距离2019-02-01,还剩下%d天" % TimeEquation.days)
print(TimeEquation.days,hours ,minutes,seconds)


"""
今天是: 2018-09-08 11:42:38
距离2019-02-01,还剩下145天
145 20.289166666666667 0.0 0.0
"""

 

日历模块


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

2、星期一是默认的每周第一天,星期天是默认的最后一天。更改设置需调用calendar.setfirstweekday()函数。

模块包含了以下内置函数:

calendar.calendar(year,w=2,l=1,c=6)

返回一个多行字符串格式的year年年历,3个月一行,间隔距离为c。 每日宽度间隔为w字符。每行长度为21* W+18+2* C。l是每星期行数。

例1:

import calendar

print(calendar.calendar(1993))

"""
上面代码的输出结果为:
                                1993

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

calendar.month(year,month,w=2,l=1)

calendar.month(year,month,w=2,l=1)

返回一个多行字符串格式的year年month月日历,两行标题,一周一行。每日宽度间隔为w字符。每行的长度为7* w+6。l是每星期的行数。

例2:

import calendar

print(calendar.month(1993,7))

"""
上面代码的输出结果为:
     July 1993
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.isleap(year)

calendar.isleap(year)
返回值:是闰年返回True,否则为false。

例3: 

import calendar

month = calendar.isleap(1993)

if month == False:
    print("1993年不是闰年")

#上面代码的输出结果为:1993年不是闰年

calendar.leapdays(y1,y2)

calendar.leapdays(y1,y2)
返回值:返回在Y1,Y2两年之间的闰年总数。

例4:

import calendar

print(calendar.leapdays(2008,2018))

#上面代码的输出结果为:3

注:calendar模块中还有其他的一些函数,由于这个模块用的不是很多,多以就不一一列举了

拓展:

UTC time:
Coordinated Universal Time,世界协调时,又称 格林尼治天文时间、世界标准时间。与UTC time对应的是各个时区的local time,东N区的时间比UTC时间早N个小时,因此UTC time + N小时 即为东N区的本地时间;而西N区时间比UTC时间晚N个小时,即 UTC time - N小时 即为西N区的本地时间; 中国在东8区,因此比UTC时间早8小时,可以以UTC+8进行表示。

猜你喜欢

转载自blog.csdn.net/qq_39314932/article/details/82052709