Datetime模块和日历模块怎么在Python项目中使用?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
<强> Datetime模块强>
<强> 1.1概述强>
Datetime比时间高级了不少,可以理解为Datetime基于时间进行了封装,提供了更多的实用的函数,Datetime的接口更加的直观,更容易调用
<强> 1.2模块中的类强>
Datetime:同时有时间与日期
timedelta:表示时间间隔,即两个时间点的间隔:主要用于计算时间的跨度
tzinfo:时区相关的信息
日期:只关注日期
<强> 2,获取系统当前时间强>
先导入模块:
import Datetime 时间=t1 datetime.datetime.now () 打印(t1)
输出:
2018-04-11 19:52:06.180339
引用><强> 3,获取指定时间强>
time2 =, datetime.datetime(2018,, 3,, 28日,21日,59岁,7日,95015) 打印(time2) print(类型(time2)输出:
2018-03-28 21:59:07.095015
引用>
& lt;类& # 39;datetime.datetime& # 39;在<强> 4,将时间转为字符串强>
time1 =, datetime.datetime.now () 时间=time3 time1.strftime (“Y % - % - % d") 打印(历史问题)输出:
2018-04-11
引用><强> 5,时间相减,返回一个时间间隔的对象强>
import datetime import 时间 时间=time1 datetime.datetime.now () time . sleep (3) 时间=time2 datetime.datetime.now () 时间=time3 time2 -time1 打印(time1) 打印(time2) 打印(历史问题) print(类型(历史问题)) #间隔天数 打印(time3.days) #,间隔天数之外的时间转为秒 打印(time3.seconds)输出:
2018-04-11 20:06:11.439085
引用>
2018-04-11 20:06:14.440052
0:00:03.000967
& lt;类& # 39;datetime.timedelta& # 39;在
0
3<强>日历模块强>
<强> 1,日历模块有很广泛的方法用来处理年历和月历强>
导入模块
import 日历<强> 2,calendar.month (year.month) 强>
返回指定年月的日历【字符串类型】
打印(calendar.month (2018 4)) print(类型(calendar.month (2018 4)))输出:
,,,,2018年4月
苏莫你我们Th Fr Sa
,,,,,,,,,,,,,,,,,,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
& lt;类& # 39;str # 39;在
引用><强> 3,calendar.calendar(年)强>
返回指定年的日历【字符串类型】
<强> 4,calendar.firstweekday() 强>
返回当前每周起始日期的设置
打印(calendar.firstweekday ())输出:
0
引用><强> 5,calendar.isleap(年)强>
返回指定的年份是否为闰年,若是返回真,否则返回假
打印(calendar.isleap (2016)输出:
真正引用>
<强> 6,calendar.leapdays(台北,year2) 强>
返回(台北,year2)之间闰年的总和。
打印(calendar.leapdays (2000、2020))输出:
5引用>
<强> 7,calendar.monthrange(年、月)强>
返回一个元组(参数一,参数二)
引用>
参数一:当月的天数
参数二:当月第一天的日期码(0,6)[周一,周日]打印(calendar.monthrange (2018,1)) 2)打印(calendar.monthrange (2018) 3)打印(calendar.monthrange (2018) print (calendar.monthrange (2018 4))输出:
(0, 31)
引用>
(28)
(3、31)
(6、30)<强> 8日calendar.monthlendar(年、月)强>
返回指定月份以每一周为元素的一个二维列表。
打印(calendar.monthcalendar (2018 4)输出:
[[0, 0, 0, 0, 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,0,0,0]]
引用><强> 9日calendar.weekday(年、月、日)强>
返回指定日期的日期码。
打印(calendar.weekday (2018 4 1)输出:
6引用>
<强> 9日获取凌晨零点到23:59的时间强>
你=,time.time () midnight =,你背后;(你%,86400),+ time.timezone 时间=pre_midnight midnight 作用;86400 时间=now_midnight midnight 安康;1 时间=start_time datetime.datetime.strptime (time.strftime (“Y % - % - % d % H: % m: % S",, time.localtime (pre_midnight)), ,,,,,,,,,,,,,,,,,,Y % - % - % d % H: % m: % S") 时间=end_time datetime.datetime.strptime (time.strftime (“Y % - % - % d % H: % m: % S",, time.localtime (now_midnight)), ,,,,,,,,,,,,,,,,,Y % - % - % d % H: % m: % S")Datetime模块和日历模块怎么在Python项目中使用