python日期与日历Datetime和Calendar模块

datetime模块

1.1 概述

datetime比time高级了不少,可以理解为datetime基于time进行了封装,提供了更多的实用的函数,datetime的接口更加的直观,更容易调用

1.2 模块中的类

datetime:同时有时间与日期

timedelta:表示时间间隔,即两个时间点的间隔:主要用于计算时间的跨度

tzinfo: 时区相关的信息

date : 只关注日期

2、获取系统当前时间

先导入模块:

import datetime

t1 = datetime.datetime.now()
print(t1)
输出:
2018-04-11 19:52:06.180339
3、获取指定时间
time2 = datetime.datetime(2018, 3, 28, 21, 59, 7, 95015)
print(time2)
print(type(time2))
输出:
2018-03-28 21:59:07.095015
<class 'datetime.datetime'>
4、将时间转为字符串
time1 = datetime.datetime.now()
time3 = time1.strftime("%Y-%m-%d")
print(time3)
输出:
2018-04-11
5、时间相减,返回一个时间间隔的对象
import datetime
import time
time1 = datetime.datetime.now()
time.sleep(3)
time2 = datetime.datetime.now()
time3 = time2 -time1
print(time1)
print(time2)
print(time3)
print(type(time3))
#间隔天数
print(time3.days)
# 间隔天数之外的时间转为秒
print(time3.seconds)
输出:
2018-04-11 20:06:11.439085
2018-04-11 20:06:14.440052
0:00:03.000967
<class 'datetime.timedelta'>
0
3
6、GMT时间格式转化
from datetime import datetime
now = datetime.utcnow() # 获取当前时间
print(now)
# 格式转换:今天是星期几,多少号,几月份,哪一年,格林尼治时间是几点几分几秒
GMT_FORMAT = '%a, %d %b %Y %H:%M:%S GMT+0800 (CST)'

date = now.strftime(GMT_FORMAT)
print(date)
GMT_FORMAT_1 = 'today is %A, %d %m %y %H:%M:%S'
date_1 = now.strftime(GMT_FORMAT_1)
print(date_1)

输出:

2020-07-28 15:00:35.429378
Tue, 28 Jul 2020 15:00:35 GMT+0800 (CST)
today is Tuesday, 28 07 20 15:00:35

格式对照表:

%a 本地的星期缩写
%A 本地的星期全称
%b 本地的月份缩写
%B 本地的月份全称
%c 本地的合适的日期和时间表示形式
%d 月份中的第几天,类型为decimal number(10进制数字),范围[01,31]
%f 微秒,类型为decimal number,范围[0,999999],Python 2.6新增
%H 小时(24进制),类型为decimal number,范围[00,23]
%I 小时(12进制),类型为decimal number,范围[01,12]
%j 一年中的第几天,类型为decimal number,范围[001,366]
%m 月份,类型为decimal number,范围[01,12]
%M 分钟,类型为decimal number,范围[00,59]
%p 本地的上午或下午的表示(AM或PM),只当设置为%I(12进制)时才有效
%S 秒钟,类型为decimal number,范围[00,61](60和61是为了处理闰秒)
%U 一年中的第几周(以星期日为一周的开始),类型为decimal number,范围[00,53]。在度过新年时,直到一周的全部7天都在该年中时,才计算为第0周。只当指定了年份才有效。
%w 星期,类型为decimal number,范围[0,6],0为星期日
%W 一年中的第几周(以星期一为一周的开始),类型为decimal number,范围[00,53]。在度过新年时,直到一周的全部7天都在该年中时,才计算为第0周。只当指定了年份才有效。
%x 本地的合适的日期表示形式
%X 本地的合适的时间表示形式
%y 去掉世纪的年份数,类型为decimal number,范围[00,99]
%Y 带有世纪的年份数,类型为decimal number
%Z 时区名字(不存在时区时为空)
%% 代表转义的"%"字符
7、把字符串转时间、获取8小时前的时间
import datetime

start_date = '2020-05-31 05:59:00'
# 把字符串转时间,并获取该时间8小时前的时间
a = datetime.datetime.strptime(start_date, '%Y-%m-%d %H:%M:%S') - datetime.timedelta(hours=8, minutes=0, seconds=0)
print(a)
print(type(a))


输出:
2020-05-30 21:59:00
<class ‘datetime.datetime’>

calendar模块

1、calendar模块有很广泛的方法用来处理年历和月历

导入模块

import calendar
2、calendar.month(year.month)

返回指定年月的日历【字符串类型】

print(calendar.month(2018,4))
print(type(calendar.month(2018,4)))

输出:
     April 2018
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

<class 'str'>
3、calendar.calendar(year)

返回指定年的日历【字符串类型】

4、calendar.firstweekday()

返回当前每周起始日期的设置

print(calendar.firstweekday())
输出:
0
5、calendar.isleap(year)

返回指定的年份是否为闰年,若是返回True,否则返回False

print(calendar.isleap(2016))
输出:
True
6、calendar.leapdays(year1,year2)

返回[year1,year2)之间闰年的总和。

print(calendar.leapdays(2000,2020))
输出:
5
7、calendar.monthrange(year,month)
返回一个元组(参数一,参数二)
参数一:当月的天数
参数二:当月第一天的日期码[0,6][周一,周日]
print(calendar.monthrange(2018,1))
print(calendar.monthrange(2018,2))
print(calendar.monthrange(2018,3))
print(calendar.monthrange(2018,4))
输出:
(0, 31)
(3, 28)
(3, 31)
(6, 30)
8、calendar.monthlendar(year,month)

返回指定月份以每一周为元素的一个二维列表。

print(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(year,month,day)

返回指定日期的日期码。

print(calendar.weekday(2018,4,1))
输出:
6
10、获取凌晨零点到23:59的时间
now = time.time()
	midnight = now - (now % 86400) + time.timezone
	pre_midnight = midnight - 86400
	now_midnight = midnight - 1
	start_time = datetime.datetime.strptime(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(pre_midnight)),
											"%Y-%m-%d %H:%M:%S")
	end_time = datetime.datetime.strptime(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(now_midnight)),
										  "%Y-%m-%d %H:%M:%S")
## 11、获取当前时间月份的首日与最后一天
import calendar

def get_month_start_and_end(date=datetime.datetime.now()):
    """
    获取当前时间的月份首日与最后一天
    :param date:
    :return: (首日,最后一天)
    """
    year, month = str(date).split('-')[0], str(date).split('-')[1]
    end = calendar.monthrange(int(year), int(month))[1]
    return f'{year}-{month}-01', f'{year}-{month}-{end}'

后记

【后记】为了让大家能够轻松学编程,我创建了一个公众号【轻松学编程】,里面有让你快速学会编程的文章,当然也有一些干货提高你的编程水平,也有一些编程项目适合做一些课程设计等课题。

也可加我微信【1257309054】,拉你进群,大家一起交流学习。
如果文章对您有帮助,请我喝杯咖啡吧!

公众号

公众号

赞赏码

关注我,我们一起成长~~

posted @ 2018-04-26 21:09  轻松学编程  阅读(169)  评论(0编辑  收藏  举报