Python基础之三个和时间相关标准库

目录

1、time模块介绍

1.1 时间戳

2.1 结构化时间对象

1.3 格式化时间的字符串

1.4 三种格式之间转换

1.5 计数函数

2、datetime模块介绍

2.1 datetime.date类

2.2 datetime.time类

2.3 datetime.datetime类(最常用)

2.4 datetime.timedalta类

3、calendar模块介绍

3.1 常用方法

3.2 Calendar类

3.3 TextCalendar类

3.4 HTMLCalendar类


1、time模块介绍

time库是python处理时间的标准库

time模块中三种时间表示方式:

1.时间戳

2.结构化时间对象

3.格式化时间字符串

1.1 时间戳

获取当前时间戳,计算内部时间值,浮点数

print(time.time())

2.1 结构化时间对象

print(time.gmtime())
time.struct_time(tm_year=2022, tm_mon=6, tm_mday=14, tm_hour=2, tm_min=33, tm_sec=49, tm_wday=1, tm_yday=165, tm_isdst=0)

函数的返回值还可以通过索引或者变量进一步获取内部变量

print(time.gmtime()[0])
print(time.gmtime().tm_mon)

转换当地时间

print(time.localtime())
print("今天是{}-{}-{}".format(time.localtime()[0], time.localtime()[1], time.localtime()[2]))

1.3 格式化时间的字符串

time.ctime()  # 获取当前时间并以易读方式表示,返回字符串

time.asctime()  # 接受时间元组,通过函数localtime()返回的时间值,返回一个可读形式字符串

如果没有提供字符串,以当前时间为准

time.strftime()  # 格式化日期

print(time.ctime())  # 获取当前时间并以易读方式表示,返回字符串

# 接受时间元组,通过函数gmtime()或localtime()返回的时间值,返回一个可读形式的字符串,如果未提供t则返回当前时间
print(time.asctime(time.localtime()))

print(time.strftime('%Y-%m-%d %H:%M:%S'))
print(time.strftime('%Y年-%m月-%d日 %H时:%M分:%S秒'))
print(time.strftime('%Y年-%m月-%d日 星期%w %H时:%M分:%S秒'))

1.4 三种格式之间转换

时间戳-结构化对象

time.localtime(时间戳)或time.gmtime(时间戳)

结构化对象-时间戳

time.mktime(结构化对象)

结构化对象-格式化时间字符串

time.strftime(格式化形式, time.localtime())或time.strftime(格式化形式, time.gmtime())

格式化时间字符串-结构化对象

strptime(str, format)  指定时间字符串

import time


# 时间戳-结构化对象
print(time.time())
print(time.gmtime())

print(time.gmtime(time.time()))

print(time.localtime())
print(time.localtime(time.time()))


# 结构化-时间戳
print(time.time())
print(time.mktime(time.localtime()))  # 精确到秒

# 结构化对象-格式化时间字符串
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))

# 格式化时间字符串-结构化对象
print(time.strptime(time.strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S'))

1.5 计数函数

time.sleep(num)  # 使用sleep(s)函数可以让该线程睡眠s秒了,s秒之后自动唤醒。s是拟休眠的时间,单位是秒,也可以是浮点数。


t1 = time.time()
time.sleep(3)
t2 = time.time()
print("执行了{:.3f}秒".format(t2-t1))

time.perf_counter()

返回性能计数器的值(以小数秒为单位),即具有最高可用分辨率的时钟,以测量短持续时间。它包括睡眠期间经过的时间,并且是系统范围的,返回值的参考点未定义,因此只有联系调用结果之间的差才有效。

start = time.perf_counter()
time.sleep(1)
end = time.perf_counter()
print("耗时:", end-start)

time.process_time()

返回当前进程的系统和用户CPU时间的总和的值(以小数秒为单位)。它不包括睡眠期间经过的时间。返回值的参考点未定义,因此只有连续调用结果之间的差异才有效。

start = time.process_time()
time.sleep(1)
end = time.process_time()
print("耗时:", end-start)

2、datetime模块介绍

datatime模块重新封装了time模块,提供了更多接口,变得更加直观和易于调用。关注如何能够更有效地解析其属性用于格式化输出和数据操作。

主要介绍四个标准类:

datetime.date

datetime.time

datetime.datetime

datetime.timedelta

2.1 datetime.date类

date类表示一个由年、月、日组成的日期,格式为:datetime.date(year, month, day)

类方法(属性)说明:

today()  # 返回当地的当前日期

fromtimestamp(timestamp)  # 根据给定的时间戳,返回本地日期

min  # date所能表示最小日期

max  # date所能表示的最大日期

resolution  # 时间间隔

print(type(datetime.date.today()))
print(datetime.date.today())
# 指定日期
print(datetime.date(1999, 8, 15))
# 根据给定时间戳返回本地日期
print(datetime.date.fromtimestamp(time.time()))


# 类属性
print(datetime.date.min)
print(datetime.date.max)
print(datetime.date.resolution)

实例方法(属性)说明

year  # 年

month  # 月

day  # 日

timetuple()  # 返回结构化时间对象struct_time

replace()  # 替换(可以替换年、月、日)

weekday()  # 返回一个整数代表星期几(0:星期一, 6:星期天)

isoweekday()  # 返回一个整数代表星期几(1:星期一, 7:星期天)

isocalendar()  # 返回格式为(year, month, day)的元组

isoformat()  # 返回格式如YYYY-MM-DD格式化的时间字符串

strftime(format)  # 返回自定义格式的字符串

# 实例属性
print(datetime.date.today().year)
print(datetime.date.today().month)
print(datetime.date.today().day)
print(datetime.date.today().weekday())
print(datetime.date.today().isoweekday())
print(datetime.date.today().isocalendar())
print(datetime.date.today().isoformat())
print(datetime.date.today().strftime('%Y年%m月%d日 %H时:%M分:%S秒'))


# 实例方法
print(datetime.date.today().timetuple())
print(datetime.date.today().replace(2001, 9, 12))
print(datetime.date.today().replace(month=2))
print(datetime.date.today().replace(day=22))

2.2 datetime.time类

time类表示由时、分、秒、微妙组成的时间,格式为:time(hour=0, minute = 0, second=0, microsecond=0,tzinfo=None,*, fold=0)。

类方法和实例属性如下:

min  # time所能表示的最小日期

max  # time所能表示的最大日期

resolution  # 时间相加的最小单位

hour  # 时

minute  # 分

second  # 秒

microsecond  # 微秒

isoformat()  # 返回格式如YYYY-MM-DD格式的时间字符串

strftime(format)  # 返回自定义格式的字符串

replace()  # 创建一个新的时间对象,用参数指定的时、分、秒、微妙代替原有对象中的属性


t = datetime.time(15, 10, 45, 888888)
print(t.min)
print(t.max)
print(t.resolution)
print(t.hour)
print(t.minute)
print(t.second)
print(t.microsecond)
print(t.isoformat())
print(t.strftime('%Y年%m月%d日 %H时:%M分:%S秒'))
print(t.replace(hour=8, minute=8))

2.3 datetime.datetime类(最常用)

datetime包括了date和time的所有信息,格式为:datetime(year, month, day, hour=0, minute=0, second=0, mircosecond=0, tzinfo=None, *, fold=0)参数范围参考date类和time类

类方法和属性如下:

today()  # 返回当地的当前时间

now(tz=None)  # 类似与today(),可选参数tz可指定时区

utcmow()  # 类似与now()返回当前UTC时间

formtimestamp(时间戳)  # 根据时间戳返回对应时间

utcfromtimestamp(时间戳)  # 根据时间戳返回UTC时间

strptime(字符串,format)  # 根据字符串(对应的格式)返回时间

combine(date, time)  # 根据date和time返回对应的时间

print(datetime.datetime.today())
print(datetime.datetime.now(tz=None))
print(datetime.datetime.utcnow())
# 时间戳 -- dt
print(datetime.datetime.fromtimestamp(time.time()))
print(datetime.datetime.utcfromtimestamp(time.time()))
# 字符串 -- dt
print(datetime.datetime.strptime('2022年03月20日 00时:00分:00秒', '%Y年%m月%d日 %H时:%M分:%S秒'))
print(datetime.datetime.combine(datetime.date(2022, 2, 2), datetime.time(2, 2, 2)))

 实例方法说明:

year  # 年

month  # 月

day  # 天

hour  # 时

minute  # 分

second  # 秒

microsecond  # 微秒

replace()  # 生成一个新的日期对象,用参数指定的年,月,日,时,分,秒代替原有对象中的属性

timestamp()  # datetime--时间戳

strftime(format)  # 返回自定义格式的字符串 


dt = datetime.datetime(2022, 6, 15, 20, 43, 45, 88888)
print(dt, type(dt))
print(dt.year)
print(dt.month)
print(dt.day)
print(dt.hour)
print(dt.minute)
print(dt.second)
print(dt.microsecond)
print(dt.replace(day=16, second=59))
print(dt.timestamp())
print(dt.strftime('%Y年%m月%d日 %H时:%M分:%S秒'))

datetime.datetime类对时间戳与时间字符串进行转换

时间戳--datetime.fromtimestamp()--datetime

datetime--dt.timestamp()--时间戳

结构化对象--time.mktime()--时间戳

datetime--dt.timetuple()--结构化对象

datetime--dt.strftime()--格式化字符串

格式化字符串--datetime.strptime()--datetime

print(time.time())
dt = datetime.datetime(2022, 2, 2, 8, 8, 58, 888888)
print(dt)
ts = dt.timestamp()
print(ts)
print(datetime.datetime.fromtimestamp(ts))
print(datetime.datetime.utcfromtimestamp(ts))
print(dt.strftime('%Y年%m月%d日 %H时:%M分:%S秒'))
print(dt.isoformat())
print(type(dt.strftime('%Y年%m月%d日 %H时:%M分:%S秒')))
date_str = dt.strftime('%Y年%m月%d日 %H时:%M分:%S秒')
print(date_str)
print(datetime.datetime.strptime(date_str, '%Y年%m月%d日 %H时:%M分:%S秒'))

2.4 datetime.timedalta类

计算时间差的类,格式:class datetime.timedalte(days=0, seconds=0, microsecond=0, milliseconds=0, hours=0, weeks=0)


# 生成时间差
td = datetime.timedelta(days=10)
print(td, type(td))

td = datetime.timedelta(days=10, hours=5)
print(td)

td = datetime.timedelta(days=10, hours=-5)
print(td)


# 计算目标日期
dt = datetime.datetime.today()
print("现在是 {} ".format(dt.strftime('%Y年%m月%d日 %H时:%M分:%S秒')))
delta = datetime.timedelta(days=10)
target = dt + delta
print("十天后是 {} ".format(target.strftime('%Y年%m月%d日 %H时:%M分:%S秒')))

dt = datetime.datetime.today()
print("现在是 {} ".format(dt.strftime('%Y年%m月%d日 %H时:%M分:%S秒')))
delta = datetime.timedelta(hours=-5)
target = dt + delta
print("五小时前是 {} ".format(target.strftime('%Y年%m月%d日 %H时:%M分:%S秒')))

# 计算时间差
dt1 = datetime.datetime.today()
dt2 = datetime.datetime.utcnow()
td = dt1 - dt2
print("我们与UTC时间差是:{}小时".format(td.seconds/3600))
print("我们与UTC时间差是:{:.0f}小时".format(td.seconds/3600))

3、calendar模块介绍

此模块允许你输出类似Unix cal程序的日历,并提供与日历相关的其他有用功能。值得注意的是,默认情况下,这些日历将星期一作为一周的第一天,将星期日作为一周的最后一天。

3.1 常用方法

month(year, month, w=0, l=0):返回一个月的日历的多行文本字符串。year指定年份,month指定月份,w每个单元格宽度,l每列换l行

print(calendar.month(2022, 6))

prcal(year, w=0, l=0, c=6, m=3):打印一年的日历,w每个单元格宽度,默认为0,内部已经做处理,最小宽度为2,l每列换l行,默认为0,内部已经做处理,c表示月与月之间的间隔宽度,默认为6,内部已经做处理,最小宽度为2, m表示将12个月分为m列。

print(calendar.prcal(2022))

calendar(year, w=2, l=1, c=6, m=3):以多行字符串形式返回一年的日历。w每个单元格宽度,l每列换l行,c表示月与月之间的间隔宽度,m表示为12个月分为m列。

print(calendar.calendar(2022))

setfirstweekday(weekday):设置每周一的开始(0表示星期一,6表示星期天)

calendar.setfirstweekday(firstweekday=1)

firstweekday():返回当前设置的每星期的第一天的数值

print(calendar.firstweekday())

 isleap(year):判断指定是否是闰年,闰年为Trued,平年为False

print(calendar.isleap(2020))
print(calendar.isleap(2021))

leapday(y1,y2):返回y1与y2年份之间闰年数量,y1与y2皆为年份。包括起始年,不包括结束年

print(calendar.leapdays(2000, 2022))

weekday(year, month, day):获取指定日期为星期几

print(calendar.weekday(2022, 6, 15))  # 返回2,为星期三

weekheader(n):返回包含星期的英文缩写,n表示英文缩写所占的宽度

print(calendar.weekheader(3))

monthrange(year, month):返回一个由一个月第一天的星期与当前月的天数组成的元组

print(calendar.monthrange(2022, 6))

monthrange(year, month):返回一个月中天数列表(不是当前月份的天数为0),按周划分,为一个二维数组。包括月份开始那周的所有日期和月份结束那周的所有日期。

print(calendar.monthcalendar(2022, 6))

3.2 Calendar类

Calendar对象提供了一些日历数据格式化的方法

iterweekdays():获取一周的数字迭代,迭代第一个值与firstweekday的值相同


c = calendar.Calendar()
print(list(c.iterweekdays()))

c = calendar.Calendar(firstweekday=6)
print(list(c.iterweekdays()))

itermonthdates(year, month):获取一个月日期的迭代器,此迭代器会返回指定月份的所有日期,包括月份开始那周的所有日期和月份结束那周的所有日期。

for item in c.itermonthdates(2022, 6):
    print(item)

3.3 TextCalendar类

Calendar子类,firstweekday为一个整数,指定一周第第一天,0是星期一(默认),6为星期日,用来生成纯文本日历。

formatmonth(year, month, w=0, l=0):以多行字符串形式返回一个日历。year指定年,month指定月,w每个单元格宽度,默认为0,内部已做处理,最小宽度为2,l每列换l行,默认为0,内部已做处理,至少换l行


c = calendar.TextCalendar()
print(c.formatmonth(2022, 6))

prmonth(theyear,themonth, w=0, l=0):打印formatmonth(theyear, themonth, w=0, l=0)的结果,无返回值

c.prmonth(2022, 6)

formatyear(theyear, w=2,l=1, c=6, m=3):以多行字符串形式返回一年日历,w每个单元格宽度,l每列换l行,c月与月之间的间隔宽度,m表示将12个月分为m列

print(c.formatyear(2022))

3.4 HTMLCalendar类

Calendar的子类,firstweekday为一个整天,指定一周的第一天,0是星期一(默认),6为星期驲

formatmonth(theyear, themonth, wirhyear=True):返回一个月日历的html内容,withyear是否显示年份,默认为True,显示年份

c = calendar.HTMLCalendar()
print(c.formatmonth(2022, 6, withyear=False))

formatyear(theyear, width=3):返回一年日历的html内容,width表示将12个月分为width列

c = calendar.HTMLCalendar()
print(c.formatyear(2022, width=2))

formatyearpage(theyear, width=3, css='calendar.css', encoding=None):返回一年日历的html内容,width表示将12个月分为width,css可以自定义css样式,encoding编码方式

print(c.formatyearpage(2022, width=4))

猜你喜欢

转载自blog.csdn.net/xiao__dashen/article/details/125273254