龙空技术网

python教程从基础到精通,第9课—日期与时间

oceansl 129

前言:

而今你们对“python计时函数”大致比较注意,各位老铁们都需要剖析一些“python计时函数”的相关知识。那么小编也在网络上网罗了一些有关“python计时函数””的相关文章,希望大家能喜欢,看官们快快来了解一下吧!

Hello,小伙伴们,祝大家五.一玩得快乐!

刚学习完了七大数据类型,今天咱们来学习日期与时间的表示方法。

Python标准库中提供了时间和日期的支持:

calendar:日历相关;

time、datetime:时间相关;

格式化当前时间:

time模块:time.strftime('%Y-%m-%d', time.localtime(time.time()))

datetime模块:datetime.datetime.now().strftime('%Y-%m-%d')

1、time模块

时间的主要三种表示方式:

1)时间戳:1970-1-1至今的秒数(float),time.time();

2)格式化时间字符串:如'2018-11- 07 20:23',time.strftime('%Y-%m-%d', struct_time);

3)结构化时间time.struct_time:包含年月日等的元组,time.localtime(tm);

1.1、时间格式化

其中,struct_time是一个9元组:

格式化输出见下表:

1.2、time模块的应用

可以获取当前时间的年月日时分秒,可以延时或计时,输出精确到毫秒(%f为微秒,去掉后三位则近似毫秒)。

光看函数很晦涩,所以咱们还是先来看一下这些函数的应用吧:

import time

#time,从 1970 年 1 月 1 日 00:00:00 到当前时间的秒数

a=time.time()

print(a)

#ctime,显示现在时间, Fri Apr 28 22:56:29 2023

print(time.ctime())

#sleep

# Start : Fri Apr 28 23:10:53 2023

# End : Fri Apr 28 23:10:53 2023

print("Start : %s" % time.ctime(a))

time.sleep(5) #浅睡眠5秒钟

print("End : %s" % time.ctime(a))

#localtime,以年月日的形式显示现在时间

#time.struct_time(tm_year=2023, tm_mon=4, tm_mday=28,

#tm_hour=23, tm_min=10, tm_sec=53, tm_wday=4, tm_yday=118, tm_isdst=0)

b=time.localtime(a)

print(b)

print(time.strftime('%Y-%m-%d %H:%M:%S',b)) # 显示年-月-日-时-分-秒

print(time.strftime('%Y-%m-%d %H:%M',b)) # 显示年-月-日-时-分

print(time.strftime('%Y-%m-%d',b)) # 2023-04-28

#gmtime

#time.struct_time(tm_year=2023, tm_mon=4, tm_mday=28, tm_hour=15,

#tm_min=10, tm_sec=53, tm_wday=4, tm_yday=118, tm_isdst=0)

print("Local time in UTC format :",time.gmtime(a))

#mktime

b=(2019,8,6,10,40,34,1,218,0)

print("Current Time in seconds :",time.mktime(b))

#asctime,Tue Aug 6 10:40:34 2019

print("Current Time in local format :",time.asctime(b))

#strftime

c = time.localtime() # get struct_time

d = time.strftime("%m/%d/%Y, %H:%M:%S", c)

print("String representing date and time:",d) #04/28/2023, 23:10:58

#strptime

e = "06 AUGUST, 2019"

f = time.strptime(e, "%d %B, %Y")

print(f)

#time.struct_time(tm_year=2019, tm_mon=8, tm_mday=6, tm_hour=0,

#tm_min=0, tm_sec=0, tm_wday=1, tm_yday=218, tm_isdst=-1)

1.3、time模块中主要函数

1.4、休眠及运行时间

2、datetime模块

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

2.1、date类

date类定义了一些常用的类方法与类属性:

示例代码:

from datetime import date

import time

print('最大日期:', date.max) #最大日期: 9999-12-31

print('最小日期:', date.min) #最小日期: 0001-01-01

print('最小日期单位:', date.resolution) #最小日期单位: 1 day, 0:00:00

print('今天日期:', date.today()) #今天日期: 2023-04-29

print('根据时间戮,返回一个date对象:', date.fromtimestamp(time.time()))

#根据时间戮,返回一个date对象: 2023-04-29

2.2、date提供的实例方法和属性

还可以作日期的加减,示例代码:

from datetime import datetime, date, timedelta

today = date.today()

print(today) #2023-04-29

print(today.year) #2023

print(today.month) #4

print(today.replace(year=2017)) #2017-04-29,今年换成2017

print(today.weekday()) #5,星期五

print(today.isoweekday()) #6,从周天开始算起第几天

print(today.isocalendar()) #datetime.IsoCalendarDate(year=2023, week=17, weekday=6)

print(today.isoformat()) # 2023-04-29,返回格式如’YYYY-MM-DD’的字符串

print(today.strftime('%Y-%m-%d')) # 2023-04-29,按"年-月-日"格式输出日期

print(today.toordinal()) # 738639,格里历的今天

import datetime

day1 = datetime.date(2020,9,1)

day2 = datetime.date(2021,9,1)

day3 = day1 + timedelta(6)

day4 = day2 - timedelta(6)

print(day2 - day1) #365 days, 0:00:00

print(day2 > day1) #True

print(day3) #2021-09-07

print(day4) #2021-08-26

2.3、time类

time类的构造函数如下:(其中参数tzinfo,它表示时区信息。)

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

time类定义的类属性:

time类提供的实例方法和属性:

像date一样,也可以对两个time对象进行比较,或者相减返回一个时间间隔对象。这里就不提供例子了。

2.4、datetime类

datetime是date与time的结合体,包括date与time的所有信息。它的构造函数如下:datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]),各参数的含义与date、time的构造函数中的一样,要注意参数值的范围。

datetime类定义的类属性与方法:

示例代码:

from datetime import datetime

import time

print('最大日期:', datetime.max)

print('最小日期:', datetime.min)

print('最小日期单位:', datetime.resolution)

print('today():', datetime.today())

print('now():', datetime.now())

print('utc样式的时间:', datetime.utcnow())

print('将本地时间作为输入:', datetime.fromtimestamp(time.time()))

print('将UTC时间作为输入:', datetime.utcfromtimestamp(time.time()))

date_str = "2022-01-01 12:00:00"

date_obj = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S') #成了日期变量

print(date_obj) #2022-01-01 12:00:00

输出结果

像date一样,也有同样的方法和属性,也可以对两个datetime对象进行比较,或者相减返回一个时间间隔对象,或者日期时间加上一个间隔返回一个新的日期时间对象。

2.5、timedelta类、tzinfo类

(1)timedelta类

通过timedelta函数返回一个timedelta对象,也就是一个表示时间间隔的对象。函数参数情况如下所示:

class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])

其没有必填参数,简单控制的话第一个整数就是多少天的间隔的意思:

datetime.timedelta(10)

两个时间间隔对象可以彼此之间相加或相减,返回的仍是一个时间间隔对象。而更方便的是一个datetime对象如果减去一个时间间隔对象,那么返回的对应减去之后的datetime对象,然后两个datetime对象如果相减返回的是一个时间间隔对象。这很是方便。

(2)tzinfo类

tzinfo是一个抽象类,不能被直接实例化。需要派生子类,提供相应的标准方法。datetime模块并不提供tzinfo的任何子类。最简单的方式是使用pytz模块。

3、Calendar模块

此模块的函数都是日历相关的,星期一是默认的每周第一天,星期天是默认的最后一天。更改设置需调用calendar.setfirstweekday()函数。

示例代码如下 :

import calendar

c0 = calendar.firstweekday() # 输出:0

calendar.setfirstweekday(1) # 设置周一为1

c1 = calendar.firstweekday() # 输出:1

print(calendar.isleap(2022)) # False

print(calendar.leapdays(2000,2022)) # 6

print(calendar.month(2022, 9, w=2, l=1)) #后面两项可省

# September 2022

# Tu We Th Fr Sa Su Mo

# 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

print(calendar.monthcalendar(2022,9))

# [[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, 0, 0, 0]]

print(calendar.monthrange(2022, 9)) # (3, 30)

print(calendar._monthlen(2022, 9)) # 30

print(calendar.weekday(2022,9,30)) # 4

print(calendar._prevmonth(2022, 1)) # (2021, 12)

print(calendar._prevmonth(2022, 4)) # (2022, 3)

print(calendar._nextmonth(2022, 12)) # (2023, 1)

print(calendar._nextmonth(2022, 9)) # (2022, 10)

愉快学习的时光总是过得很快,一不小心又到结尾啦。

先来给自己一个奖励,双手举起,yeah!

有什么问题可以关注我/私信我/加好友,让我们一起成长吧。

标签: #python计时函数