目录
2.2.2 time.localtime([secs]):将一个时间戳转换为当前时区的struct_time,即时间元组格式的时间
2.2.3 time.gmtime([secs]):将一个时间戳转换为UTC时区(0时区)的struct_time
2.2.4 time.mktime():将一个struct_time转化为时间戳
2.2.6 time.clock():睡眠函数,python 3.8之后clock()被移除了,可以使用time.perf_counter()或time.process_time()
2.2.6 time.strftime()返回字符串表示的当地时间
2.2.7 time.strptime():将格式字符串转化成struct_time
3.3.1 date.today():返回一个表示当前本地今天日期的date对象
3.3.2 date.fromtimestamp():根据给定的时间戳timestamp,返回一个date对象
3.3.3 date.weekday():返回weekday中的星期几
3.3.4 date.isoweekday():返回weekday中的星期几
3.3.5 date.isocalendar():返回时间对象的year/week/weekday(工作日)
3.3.6 date.strftime(fmt):返回自定义的格式时间字符串
3.4.1 time类的属性-hour、minute、second、 microsecond
3.4.2 time.replace():用给的的参数时分秒替换原有对象中的属性
3.4.3 time.isoformat():返回格式如:HH:MM:SS的时间字符串
3.4.4 time.strftime():返回自定义格式时间字符串
3.5.1 datetime.today():返回当前本地时间的datetime对象
3.5.2 datetime.now(tz):返回当前本地时间的datetime对象
3.5.3 datetime.fromtimestamp(timestamp[,tz]):根据时间戳创建一个datetime对象
3.5.4 datetime.strptime():将格式时间字符串转换成datetime对象
3.5.5 datetime类的属性-year、month、day、hour、minute、second
3.5.6 datetime.date():获取时间中的日期对象date
3.5.7 datetime.time():获取时间中的时间对象time
3.5.8 datetime.combine(date,time):根据date和time创建datetime对象
3.5.9 datetime.replace():替换原有时间,获得新的日期时间
3.5.10 mktime():将datetime对象转换成时间戳
3.5.11 datetime.weekday(time):返回一周中的星期几
3.5.12 datetime.isocaendar(time):以元组形式返回年月日
3.5.13 datetime.strftime(format):返回自定义的格式时间字符串
3.6.3 timedelta.total_seconds():获取总秒数
4.1.3 calendar.month_name:月的全称
4.1.4 calendar.month_abbr:月的简称
4.2.1 calendar.isleap(year):判断是否为闰年
4.2.2 calendar.month(year,month,w=2,I=1):返回指定年的某月
4.2.3 calendar.calenda(year,w=2,I=1,c=6):返回指定年的日历
4.2.4 calendar.HTMLCalendar():返回指定年的日历,html格式
一、基本概念
在python中与时间处理相关的模块有:time、datatime和calender
在python中表示时间的方式有:时间戳、格式化的时间字符串、元组(struct_time共9种元素)。由于time模块主要是调用c库实现的,所以在不同的平台可能会不同。
- 时间戳(timestamp):表示从1970年1月1号00:00:00开始到现在按秒计算的偏移量。tick单位(系统的相对时间,间隔以秒为单位的浮点数)最适合做日期运算。但是1970年之前的时间无法表示,UNIX和win都只支持到2038年某日。 type(time.time())返回的是float类型,返回时间戳的函数主要有time()、clock()等
- UTC(世界协调时),就是格林威治天文时间。在中国为UTC+8,DST夏令时。
- 元组方式:struct_time共有9个元素,返回struct_time的函数主要有gmtime()、localtime()、strptime()
二、time模块
2.1 时间元组
序号 | 属性 | 值 | 说明 |
1 | tm_year | 2008 | 4位数的年份 |
2 | tm_mon | 1-12 | 月份 |
3 | tm_mday | 1-31 | 日 |
4 | tm_hour | 0-23 | 时 |
5 | tm_min | 0-59 | 分钟 |
6 | tm_sec | 0-61(60或61是闰秒) | 秒 |
7 | tm_wday | 0-6(0是周一) | 一周的第几天 |
8 | tm_yday | 1-366(日历) | 一年的第几天 |
9 | tm_isdst | -1,0,1 | 其中-1是决定是否为夏令时 |
本地时间
#encoding=utf-8
import time
ls = time.localtime()
print(ls) # 时间元组
# 直接使用元组索引获取对应项的值
print("year:",ls[0])
print("month:",ls[1])
print("day:",ls[2])
#使用成员符号调用
print("year:",ls.tm_year)
print("month:",ls.tm_mon)
print("day:",ls.tm_mday)
格林威治时间
import time
ls = time.gmtime()
print(ls)
2.2 常用函数
2.2.1 time.time():返回当前时间的时间戳
>>> import time
>>> print(time.time())#表示当前时间距离1970年1月1日的秒数
1651716585.707484
>>> #对时间戳取整
>>> print(int(time.time()))
1651716586
2.2.2 time.localtime([secs]):将一个时间戳转换为当前时区的struct_time,即时间元组格式的时间
sec -- 转换为time.struct_time类型的对象的秒数。如果secs参数未提供,则以当前时间为准(即会默认调用time.time())
#未给定参数,默认会调用time.time()
>>> time.localtime()
time.struct_time(tm_year=2022, tm_mon=5, tm_mday=5, tm_hour=10, tm_min=12, tm_sec=21, tm_wday=3, tm_yday=125, tm_isdst=0)
>>> time.localtime(1440337405.85)
#给定参数
>>> time.localtime(1440337405.85)
time.struct_time(tm_year=2015, tm_mon=8, tm_mday=23, tm_hour=21, tm_min=43, tm_sec=25, tm_wday=6, tm_yday=235, tm_isdst=0)
2.2.3 time.gmtime([secs]):将一个时间戳转换为UTC时区(0时区)的struct_time
参数secs--表示从1970-1-1 00:00:00以来的秒数。其默认值为time.time()
>>> time.gmtime()
time.struct_time(tm_year=2022, tm_mon=5, tm_mday=5, tm_hour=2, tm_min=19, tm_sec=19, tm_wday=3, tm_yday=125, tm_isdst=0)
>>> time.gmtime(123456.80)
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=2, tm_hour=10, tm_min=17, tm_sec=36, tm_wday=4, tm_yday=2, tm_isdst=0)
2.2.4 time.mktime():将一个struct_time转化为时间戳
➢ time.mktime() 函数执行与gmtime(), localtime()相反的操作,它接收struct_time对象作为参数,返回用秒数表示时间的浮点数。
➢ 参数:t -- 结构化的时间或者完整的9位元组元素。 如果输入的值不是一个合法的时间,将触发 OverflowError 或 ValueError。
>>> struct_time = time.localtime()
>>> struct_time
time.struct_time(tm_year=2022, tm_mon=5, tm_mday=5, tm_hour=10, tm_min=22, tm_sec=42, tm_wday=3, tm_yday=125, tm_isdst=0)
>>> time.mktime(struct_time)
1651717362.0
2.2.5 time.sleep():睡眠函数
单位为秒
time.sleep(10)#睡眠10秒钟
2.2.6 time.clock():睡眠函数,python 3.8之后clock()被移除了,可以使用time.perf_counter()或time.process_time()
以浮点数计算的秒数返回当前的CPU时间,用来衡量不同程序的耗时, 比time.time()更有用.返回的是当前处理器时间作为Unix上以秒为单位的浮点数。记的是CPU耗时,当前python进程在CPU上花费的时间
perf_counter()会包含sleep()休眠时间,适用测量短持续时间
process_time()不包括sleep()休眠时间期间经过的时间
import time
def procedure() :
time.sleep(5)
time1 = time.perf_counter()
procedure()
print (time.perf_counter() - time1, "seconds process time!")
#使用time.time()来计算程序耗时
time2 = time.time()
procedure()
print (time.time() - time2, "seconds!")
2.2.6 time.strftime()返回字符串表示的当地时间
把一个代表时间的元组或者struc_time(如由time.localtime()或time.gmtime()返回)转化为格式化的时间字符串,格式由参数format决定;没有指定的话,将传入time.localtime();如果元组中任何一个元素越界会跑出ValueError异常;函数返回的是一个可读表示的本地时间字符串。
命令格式:time.strftime(format,[t])
参数说明:format--是一个格式化字符串
t:可选的参数,是一个struc_time对象
- 时间字符串的格式化符号:
符号 | 说明(区分大小写) |
%a | 本地星期名称的简写(如星期四为Thu) |
%A | 本地星期名称的全称(如星期四为Thursday) |
%b | 本地月份名称的简写(如八月份为agu) |
%B | 本地月份名称的全称(如八月份为aguust) |
%c | 本地相应的日期和时间的字符串表示(如:15/08/27 10:20:06) |
%d | 一个月中的第几天(01-31) |
%H | 一天中的第几个小时(24小时制,00-23) |
%I | 第几个小时(12小时制,0 -11) |
%j | 一年中的第几天(001 -366) |
%m | 月份(01-12) |
%M | 分钟数(00-59) |
%p | %p 本地am或者pm的相应符 |
%S | 秒(00 -61) |
%U | 一年中的星期数。(00 -53星期天是一个星期的开始。)第一个星期天之前的所有天数都放在第0周。 |
%w | 一个星期中的第几天(0 -6,0是星期天) |
%W | 和%U基本相同,不同的是%W以星期一为一个星期的开始。 |
%x | 本地相应日期字符串(如15/08/01) |
%X | 本地相应时间字符串(如08:08:10) |
%y | 去掉世纪的年份(00 -99)两个数字表示的年份 |
%Y | 完整的年份(4个数字表示年份) |
%z | 与UTC时间的间隔(如果是本地时间,返回空字符串) |
%Z | 时区的名字(如果是本地时间,返回空字符串) |
%% | “%”字符 |
>>> import time
>>> #获取当前时间的struct_time对象
>>> formatTime = time.localtime()
>>> print(formatTime)
time.struct_time(tm_year=2022, tm_mon=5, tm_mday=5, tm_hour=22, tm_min=27, tm_sec=42, tm_wday=3, tm_yday=125, tm_isdst=0)
>>> #格式化时间字符串
>>> strTime = time.strftime("%Y-%m-%d %H:%M:%S",formatTime)
>>> print(strTime)
2022-05-05 22:27:42
- 直接使用字符串拼接成格式时间字符串
>>> formatTime = time.localtime()
>>> print (formatTime)
time.struct_time(tm_year=2022, tm_mon=5, tm_mday=5, tm_hour=22, tm_min=34, tm_sec=56, tm_wday=3, tm_yday=125, tm_isdst=0)
>>> #直接使用字符串拼接成格式时间字符串
>>> print (str(formatTime.tm_year) + "年" + str(formatTime.tm_mon) + "月" +
... str(formatTime.tm_mday) + "日" +str(formatTime.tm_hour) + "点"
... +str(formatTime.tm_min)+"分"+str(formatTime.tm_sec)+"秒")
2022年5月5日22点34分56秒
- 将当前时间的时间戳转换成想要的时间格式字符串
>>> import time
>>> import locale
>>> locale.setlocale(locale.LC_CTYPE,"chinese")
'Chinese_China.936'
>>> strTime = time.strftime("%Y年-%m月-%d日 %H:%M:%S",time.localtime())
>>> print(strTime)
2022年-05月-05日 22:37:58
- 获取当前时间的年月日小时分钟秒
>>> print(time.strftime("%Y/%m/%d %H:%M:%S"))
2022/05/05 22:39:19
>>> now = time.localtime()
>>> print (now)
time.struct_time(tm_year=2022, tm_mon=5, tm_mday=5, tm_hour=22, tm_min=41, tm_sec=3, tm_wday=3, tm_yday=125, tm_isdst=0)
>>> #获取当前时间的格式化时间
>>> print (time.strftime('%Y-%m-%d %H:%M:%S', now))
2022-05-05 22:41:03
>>> #星期的简写
>>> print (time.strftime('%a', now))
Thu
>>> #星期的全写
>>> print (time.strftime('%A', now))
Thursday
>>> #月份的简写
>>> print (time.strftime('%b', now))
May
>>> #月份的全写
>>> print (time.strftime('%B', now))
May
>>> #得到日期时间的字符串
>>> print (time.strftime('%c', now))
Thu May 5 22:41:03 2022
>>> #日期字符串
>>> print (time.strftime('%x', now))
05/05/22
>>> #时间字符串
>>> print (time.strftime('%X', now))
22:41:03
>>> #今天在这周是星期几
>>> print (time.strftime('%w', now))
4
>>> #今天是今年的第几天
>>> print (time.strftime('%j', now))
125
>>> #这周是今天的第几周
>>> print (time.strftime('%U', now))
18
2.2.7 time.strptime():将格式字符串转化成struct_time
是time.strftime()的逆操作,返回的是一个struc_time对象
命令格式:time.strftime(string,format)
参数说明:string--时间字符串
format--是一个格式化字符串
注意:
在使用strptime()函数将一个指定格式的时间字符串转化成元组时,参数format的格式必须和string的格式保持一致,如果string中日期间使用“-”分隔,format中也必须使用“-”分隔,时间中使用冒号“:”分隔,后面也必须使用冒号分隔,否则会报格式不匹配的错误
>>> #创建一个时间字符串变量stime
>>> stime = "2015-08-24 13:01:30"
>>> #通过strptime()函数将stime转化成strcut_time形式
>>> formattime = time.strptime(stime,"%Y-%m-%d %H:%M:%S")
>>> print (formattime)
time.struct_time(tm_year=2015, tm_mon=8, tm_mday=24, tm_hour=13, tm_min=1, tm_sec=30, tm_wday=0, tm_yday=236, tm_isdst=-1)
>>> #遍历返回的时间元组序列
>>> for i in formattime :
... print (i ,end="")
...
2015824131300236-1>>>
三、datetime模块
是基于time包的一个高级包。datetime可以理解为date和time两个部分组成:date指年月日构成的日期(相当于日历),time是指时分秒微秒构成的一天24小时中的具体时间(相当于手表)。由此可以将这两个分开管理(datetime.date类, datetime.time类),也可以将两者合并在一起(datetime.datetime类)。下面就分别介绍一 下datetime模块中的这几个类。
3.1 引入datetime模块
3.2 datetime模块常用类
datetime.date:日期类。常用的属性有year,month,day;
datetime.time:时间类。常用的属性有hour,minute,second,microsecond; datetime.timedelta:表示时间间隔,即两个时间点之间的长度。
datetime.tzinfo:与时区有关的信息。
3.3 date类常用方法
构造函数:
date类是一个日期类,由年、月、日组成,该类的构造函数如下:
class datetime.date(year, month, day):
参数说明:year--表示年,范围(MINYEAR, MAXYEAR],即[1, 9999]
month--表示月,范围[1, 12]
day--某个月中第几天,最大值根据给定的year,month参数来决定。例如闰年2 月份有29天
date对象所能表示的最大和最小日期,返回的是datetime.date类型对象
>>> import datetime
>>> #获取date能表示的最大日期
>>> print (datetime.date.max)
9999-12-31
>>> #获取date能表示的最小日期
>>> print (datetime.date.min)
0001-01-01
3.3.1 date.today():返回一个表示当前本地今天日期的date对象
>>> t=datetime.date.today()
>>> t
datetime.date(2022, 5, 5)
>>> print(t)
2022-05-05
3.3.2 date.fromtimestamp():根据给定的时间戳timestamp,返回一个date对象
>>> import time
>>> import datetime
>>> #获取当前时间的时间戳
>>> now = time.time()
>>> print (now)
1651762730.6345298
>>> #将时间戳转换为date类型的时间
>>> s = datetime.date.fromtimestamp(now)
>>> print (s)
2022-05-05
3.3.3 date.weekday():返回weekday中的星期几
星期一,返回0;星期二,返回1;以此类推
函数格式:date.weekday(s)
参数说明:s--datetime.date类型的参数
>>> now=datetime.date.today()
>>> print(now)
2022-05-05
>>> print(datetime.date.weekday(now))
3
3.3.4 date.isoweekday():返回weekday中的星期几
星期一,返回1;星期二,返回2;以此类推。
函数格式:date.isoweekday(s)
参数说明:s--datetime.date类型的参数
>>> print(datetime.date.isoweekday(now))
4
3.3.5 date.isocalendar():返回时间对象的year/week/weekday(工作日)
函数格式:date.isocalendar(s)
参数说明:s--datetime.date类型的参数
>>> now = datetime.datetime.now()
>>> print (now)
2022-05-05 23:04:14.968825
>>> s = datetime.date.isocalendar(now)
>>> print (s)
datetime.IsoCalendarDate(year=2022, week=18, weekday=4)
3.3.6 date.strftime(fmt):返回自定义的格式时间字符串
函数格式:date.strftime(format)
参数说明:format--自定义的时间格式
>>> now = datetime.datetime.now()
>>> print (now)
2022-05-05 23:05:45.920029
>>> otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S")
>>> print (otherStyleTime)
2022-05-05 23:05:45
3.3.7 日期加上一个时间间隔
dateNow = dateOld + timedelta #timedelta表示时间间隔,后面会介绍。
日期加上一个间隔,返回一个新的日期对象。
>>> from datetime import *
>>> #获取今天的日期
>>> today = date.today()
>>> print (today)
2022-05-05
>>> #在今天的日期上再加10天
>>> print (today + timedelta(days = 10))
2022-05-15
3.3.8 日期减去一个时间间隔
dateNow = dateOld - timedelta #timedelta表示时间间隔,后面会介绍。
日期减去一个间隔,返回一个新的日期对象。
>>> from datetime import *
>>> #获取今天的日期
>>> today = date.today()
>>> print (today)
2022-05-05
>>> #在今天的日期上再减10天
>>> print (today - timedelta(days = 10))
2022-04-25
3.3.9 两个日期相减
timedelta = date1- date2
返回两个日期间的间隔对象
>>> from datetime import *
>>> #获取今天的日期
>>> today = date.today()
>>> print (today)
2022-05-05
>>> #替换形成一个新的日期
>>> future = today.replace(day = 15)
>>> print (future)
2022-05-15
>>> #算一下两日期间的间隔
>>> delta= future - today
>>> print (delta)
10 days, 0:00:00
>>> #在原日期上添加一个日期间隔
>>> print (future + delta)
2022-05-25
3.3.10 比较日期大小
date1 < date2 返回比较结果布尔值,真返回True,假返回False
>>> #今天的日期
>>> now = date.today()
>>> print (now)
2022-05-05
>>> #未来的日期
>>> tomorrow = now.replace(day = 13)
>>> print (tomorrow)
2022-05-13
>>> #比较两日期大小
>>> print (tomorrow > now)
True
>>> print (tomorrow < now)
False
3.4 time类
构造函数
time类是一个时间类,由时、分、秒、微秒组成,该类的构造函数如下:
参数说明:hour--表示小时,范围[0,24)
minute--表示分,范围[0,60)
second--表示秒,范围[0,60)
microsecond--表示微秒,范围[0, 1000000)
tzinfo--表示时区信息。
#获取time能表示的最小时间
>>> print(datetime.time.min)
00:00:00
#获取time能表示的最大时间
>>> print(datetime.time.max)
23:59:59.999999
3.4.1 time类的属性-hour、minute、second、 microsecond
>>> from datetime import *
>>> # tm = time(23, 46, 10)
>>> tm = datetime.now()
>>> print (tm)
2022-05-05 23:17:48.511427
>>> print (tm.hour)
23
>>> print (tm.minute)
17
>>> print (tm.second)
48
>>> print (tm.microsecond)
511427
3.4.2 time.replace():用给的的参数时分秒替换原有对象中的属性
创建的是一个新的对象,原有的对象并没有改变
>>> from datetime import *
>>> tm = datetime.now()
>>> print (tm)
2022-05-05 23:19:42.048996
>>> tm1 = tm.replace(hour = 12, minute = 10)
>>> print (tm1)
2022-05-05 12:10:42.048996
>>> print (tm)
2022-05-05 23:19:42.048996
3.4.3 time.isoformat():返回格式如:HH:MM:SS的时间字符串
>>> tm = time(23, 46, 10)
>>> print (tm)
23:46:10
>>> tm1 = tm.isoformat()
>>> print (tm1)
23:46:10
3.4.4 time.strftime():返回自定义格式时间字符串
>>> tm = time(23, 46, 10)
>>> print (tm)
23:46:10
>>> tm1 = tm.strftime("%H-%M-%S")
>>> print (tm1)
23-46-10
3.5 datetime类
datetime类是date和time的结合体,包括date与time的所有信息, date和time类中具有的方法和属性,datetime类都具有。所以在我们日常的工作中,可以仅使用datetime类。由于datetime类是date和time两部分组成的,所以其很多的实例方法与属性都跟date和time都一样的
构造函数:
参数说明:和date/time类的构造函数一样
3.5.1 datetime.today():返回当前本地时间的datetime对象
>>> from datetime import *
>>> datetime.today()
datetime.datetime(2022, 5, 6, 7, 44, 37, 21089)
3.5.2 datetime.now(tz):返回当前本地时间的datetime对象
如果给定了参数tz,则获取tz所指时区的本地时间,不传的话默认本地时区
>>> from datetime import *
>>> tm = datetime.now()
>>> print (tm)
2022-05-06 07:46:22.575511
>>> print (tm.year)
2022
>>> print (tm.month)
5
>>> print (tm.day)
6
>>> print (tm.hour)
7
>>> print (tm.minute)
46
>>> print (tm.second)
22
>>> print (tm.microsecond)
575511
>>> tm1=datetime.now(timezone(timedelta(hours=-4)))
>>> tm1
datetime.datetime(2022, 5, 5, 19, 52, 10, 636979, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))
3.5.3 datetime.fromtimestamp(timestamp[,tz]):根据时间戳创建一个datetime对象
参数tz指定时区信息,不传默认为本地时区。
>>> t = time.time()
>>> print(t)
1651795050.547898
>>> #将时间戳转换为一个datetime对象
>>> datetimes = datetime.fromtimestamp(t)
>>> print(datetimes)
2022-05-06 07:57:30.547898
>>> print(type(datetimes))
<class 'datetime.datetime'>
>>> print(str(datetimes))
2022-05-06 07:57:30.547898
3.5.4 datetime.strptime():将格式时间字符串转换成datetime对象
>>> import datetime
>>> print (datetime.datetime.strptime("2015-08-27 17:23:05", "%Y-%m-%d %H:%M:%S"))
2015-08-27 17:23:05
3.5.5 datetime类的属性-year、month、day、hour、minute、second
>>> import datetime
>>> t = datetime.datetime.now()
>>> print ("当前的日期和时间是 %s" % t)
当前的日期和时间是 2022-05-06 08:04:27.043628
>>> print ("当前的年份是 %s" %t.year)
当前的年份是 2022
>>> print ("当前的月份是 %s" %t.month)
当前的月份是 5
>>> print ("当前的日期是 %s" %t.day)
当前的日期是 6
>>> print ("dd/mm/yyyy 格式是 %s/%s/%s" % (t.day, t.month, t.year) )
dd/mm/yyyy 格式是 6/5/2022
>>> print ("当前小时是 %s" %t.hour)
当前小时是 8
>>> print ("当前分钟是 %s" %t.minute)
当前分钟是 4
>>> print ("当前秒是 %s" %t.second)
当前秒是 27
3.5.6 datetime.date():获取时间中的日期对象date
>>> import datetime
>>> dates = datetime.datetime.date(datetime.datetime.today())
>>> print (type(dates))
<class 'datetime.date'>
>>> print (dates)
2022-05-06
>>> print (dates.year)
2022
3.5.7 datetime.time():获取时间中的时间对象time
>>> import datetime
>>> times = datetime.datetime.time(datetime.datetime.today())
>>> print (type(times))
<class 'datetime.time'>
>>> print (times)
08:08:50.046981
>>> print (times.hour)
8
3.5.8 datetime.combine(date,time):根据date和time创建datetime对象
参数说明:date--是datetime.date对象
time--是datetime.time对象
>>> import datetime
>>> print(datetime.datetime.combine(datetime.datetime.today(),datetime.time(17,12,35)))
2022-05-06 17:12:35
>>> datetime.datetime.today()
>>> print(datetime.datetime.combine(datetime.date(2022,4,20),datetime.time(17,12,35)))
2022-04-20 17:12:35
3.5.9 datetime.replace():替换原有时间,获得新的日期时间
>>> times = datetime.datetime.today()
>>> print (times)
2022-05-06 08:16:01.826716
>>> #替换原有时间,获得新的日期时间
>>> tmp = times.replace(year = 2017, hour = 23)
>>> print (tmp)
2017-05-06 23:16:01.826716
3.5.10 mktime():将datetime对象转换成时间戳
>>> #获取当前时间的datetime对象
>>> t = datetime.datetime.now()
>>> print (t)
2022-05-06 08:18:08.758227
>>> #根据当前时间的datetime对象获取当前时间的时间元组
>>> struct_time = t.timetuple()
>>> print (struct_time)
time.struct_time(tm_year=2022, tm_mon=5, tm_mday=6, tm_hour=8, tm_min=18, tm_sec=8, tm_wday=4, tm_yday=126, tm_isdst=-1)
>>> #根据当前时间的时间元组获得当前时间的时间戳
>>> timestamp = time.mktime(struct_time)#注意是time类中的方法
>>> #对时间戳取整
>>> timestamp = int(timestamp)
>>> print (timestamp)
1651796288
3.5.11 datetime.weekday(time):返回一周中的星期几
参数time是一个datetime.date类型的数据。返回weekday中的 星期几,星期一,返回0;星期二,返回1;以此类推。
>>> import datetime
>>> now = datetime.date.today()
>>> print (now)
2022-05-06
>>> #查看今天是这周的第几天
>>> print (datetime.date.weekday(now)) #用的date.weekday()方法
4
>>> print (datetime.datetime.weekday(now))
4
3.5.12 datetime.isocaendar(time):以元组形式返回年月日
参数time是一个datetime.date类型的数据。
>>> now = datetime.date.today()
>>> print (now)
2022-05-06
>>> #以元组的形式返回年月日
>>> print (datetime.datetime.isocalendar(now))
datetime.IsoCalendarDate(year=2022, week=18, weekday=5)
3.5.13 datetime.strftime(format):返回自定义的格式时间字符串
>>> import datetime
>>> now=datetime.datetime.now()
>>> print(now)
2022-05-06 08:25:45.952216
>>> #获取当前时间的格式化时间字符
>>> print(now.strftime(('%Y-%m-%d %H:%M:%S %f')))
2022-05-06 08:25:45 952216
>>> print(now.strftime(('%y-%m-%d %I:%M:%S %p')))
22-05-06 08:25:45 AM
>>>
>>> #星期的简写
>>> print (now.strftime('%a'))
Fri
>>> #星期的全写
>>> print (now.strftime('%A'))
Friday
>>>
>>> #月份的简写
>>> print (now.strftime('%b'))
May
>>> #月份的全写
>>> print (now.strftime('%B'))
May
>>>
>>> #得到日期时间的字符串
>>> print (now.strftime('%c'))
Fri May 6 08:25:45 2022
>>> #得到日期的字符串
>>> print (now.strftime('%x'))
05/06/22
>>> #得到时间的字符串
>>> print (now.strftime('%X'))
08:25:45
>>>
>>> #今天是星期几
>>> print (now.strftime('%w'))
5
>>>
>>> #今天是今年的第几天
>>> print (now.strftime('%j'))
126
>>> #今天是今年的第几周
>>> print (now.strftime('%U'))
18
3.6 timedelta类
datetime.timedelta类对象代表两个时间之间的时间差,两个date或 datetime对象相减就可以返回一个timedelta对象。
构造函数:
参数说明:所有的参数都是可选的,并且默认是0;参数的值可以是整数、浮点数、整数或负数
针对时间存储,timedelta内部只能存储days、seconds、microseconds,其它值自动按如下规则转换:
1 millisecond(毫秒)转换成 1000 microseconds(微秒)
1 minute 转换成 60 seconds
1 hour 转换成 3600 seconds
1 week转换成 7 days
3.6.1 两个日期的时间相减
两个时间相减时,就会返回一个datetime.timedelta时间对象,代表两个时间之间的时间差。
>>> import datetime
>>> #求两个日期间的天数差
>>> d1 = (datetime.datetime(2015, 7, 5))
>>> d2 = (datetime.datetime(2015, 8, 26))
>>> print ((d2 - d1).days)
52
3.6.2 日期或时间加上或减去一个时间间隔
加上或减去的时间间隔是通过加减timedelta对象中的属性值给定的值实现的
代码示例:(1)计算明天的此时的时间
#coding=utf-8
import datetime
#获取当前的时间
now = datetime.datetime.now()
print (now)
#设定一个时间间隔,间隔为一天
delta = datetime.timedelta(days = 1)
newTime = now + delta
print (newTime)
#得到明天的时间
print (str(newTime)[:-7])
#或者使用格式化函数
print (newTime.strftime('%Y-%m-%d %H:%M:%S'))
#原时间减1天
delta = datetime.timedelta(days = -1)
newTime = now + delta
print (newTime)
代码示例:(2)计算100天前的日期
#coding=utf-8
from datetime import datetime
from datetime import timedelta
now = datetime.now()
#设置100天前的时间间隔
delta = timedelta(days = -100)
#得到100天前的时间
oldTime = now + delta
print (oldTime.strftime("%Y-%m-%d"))
#或者:
import datetime
print (datetime.date.today() + datetime.timedelta(days=-100))
代码示例:(3)计算3小时前的时间
import datetime
threeHoursAgo = datetime.datetime.now() - datetime.timedelta(hours = 3)
print (str(threeHoursAgo)[:-7])
3.6.3 timedelta.total_seconds():获取总秒数
>>> import datetime
>>> #计算给定时间间隔的总秒数
>>> seconds = datetime.timedelta(hours=1, seconds=30).total_seconds()
>>> print (seconds)
3630.0
四、calendar模块
calendar就是日历模块,提供了一些操作日期、生成日历的方法,使用前需要import calendar导入
1、calendar.Calendar(firstweekday=0)该类提供了许多生成器,如星期的生成器,某月日历生成器。
2、calendar.TextCalendar(firstweekday = 0)该类提供了按月、按年生成日历字符串的方法。
3、calendar.HTMLCalendar(firstweekday = 0)类似TextCalendar,只是生成器是HTML格式日历。
4.1 常用属性
4.1.1 calendar.day_name:星期的全称
>>> import calendar
>>> for i in calendar.day_name :
... print (i,end=" ")
...
Monday Tuesday Wednesday Thursday Friday Saturday Sunday >>>
4.1.2 calendar.day_abbr:星期的简称
>>> for i in calendar.day_abbr :
... print(i,)
...
Mon
Tue
Wed
Thu
Fri
Sat
Sun
4.1.3 calendar.month_name:月的全称
>>> for i in calendar.month_name :
... print (i,end=" ")
...
January February March April May June July August September October November December >>>
4.1.4 calendar.month_abbr:月的简称
>>> for i in calendar.month_abbr:
... print(i,end=" ")
...
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec >>>
4.2 常用方法
4.2.1 calendar.isleap(year):判断是否为闰年
>>> import calendar
>>> #判断2015年是否是闰年
>>> if calendar.isleap(2015) is True :
... print ("2015年是闰年")
... else :
... print ("2015年不是闰年")
...
2015年不是闰年
4.2.2 calendar.month(year,month,w=2,I=1):返回指定年的某月
返回一个多行字符串格式的年月日历,两行标题,一周一行。每日宽度间隔为w字符。每行的长度 为7* w+6。l是每星期的行数。
>>> import calendar
>>> print (calendar.month(2015, 3, 1, 1))
March 2015
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
>>> print (calendar.month(2015, 3, 1, 2))
March 2015
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
4.2.3 calendar.calenda(year,w=2,I=1,c=6):返回指定年的日历
返回一个多行字符串格式的年历,3个月一行, 间隔距离为c。每日宽度间隔为w字符。每行长度为21* W+18+2* C。l是每星期行数。 返回指定年的日历,按日历格式返回一年12个月的日历。
>>> import calendar
>>> print (calendar.calendar(2015, 3, 1, 1))
2015
January February March
Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun
1 2 3 4 1 1
5 6 7 8 9 10 11 2 3 4 5 6 7 8 2 3 4 5 6 7 8
12 13 14 15 16 17 18 9 10 11 12 13 14 15 9 10 11 12 13 14 15
19 20 21 22 23 24 25 16 17 18 19 20 21 22 16 17 18 19 20 21 22
26 27 28 29 30 31 23 24 25 26 27 28 23 24 25 26 27 28 29
30 31
April May June
Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun
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
Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun
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
Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat Sun
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
4.2.4 calendar.HTMLCalendar():返回指定年的日历,html格式
返回一个多行字符串格式的year年month月日历,两行标题,一周一行。每日宽度间隔为w字符。每行的长度为7* w+6。l是每星期的行数
'''HTMLCalendar'''
import calendar
myCal=calendar.HTMLCalendar(calendar.SUNDAY)
print(myCal.formatmonth(2022,5))
with open('calendar.html','w') as fp:
fp.write(myCal.formatmonth(2022,5))