Python程序可以通过多种方式处理日期和时间。日期格式之间的转换是计算机常见问题。Python的时间(time)和日历(calendar)模块可用于跟踪日期和时间。
一些常用代码示例
- 获取当前时间和日期,如:2018-08-18 12:12:00
- 计算两个日期相差天数
- 计算程序运行的时间
#!/usr/bin/python3
#coding=utf-8
import time
import datetime
starttime = datetime.datetime.now()
time.sleep(5)
endtime = datetime.datetime.now()
print ((endtime - starttime).seconds )
- 计算十天之后的日期时间
#!/usr/bin/python3
#coding=utf-8
import time
import datetime
d1 = datetime.datetime.now()
d3 = d1 + datetime.timedelta(days =10)
print (str(d3))
print (d3.ctime())
- 获取两个日期时间的时间差
t = (datetime.datetime(2019,1,13,12,0,0) - datetime.datetime.now()).total_seconds()
print ("t = ", t)
## 输出结果
t = 49367780.076406
Python中有提供与日期和时间相关的4个模块。它们分别是 -
| 模块 | 说明 |
|---|---|
time |
time是一个仅包含与日期和时间相关的函数和常量的模块,在本模块中定义了C/C++编写的几个类。 例如,struct_time类。 |
datetime |
datetime是一个使用面向对象编程设计的模块,可以在Python中使用日期和时间。它定义了几个表示日期和时间的类。 |
calendar |
日历是一个提供函数的模块,以及与Calendar相关的几个类,它们支持将日历映像生成为text,html,…. |
locale |
该模块包含用于格式化或基于区域设置分析日期和时间的函数。 |
1. 时间间隔
时间间隔是以秒为单位的浮点数。 从1970年1月1日上午12:00(epoch),这是一种时间的特殊时刻表示。
在Python中,当前时刻与上述特殊的某个时间点之间以秒为单位的时间。这个时间段叫做Ticks。

time模块中的time()函数返回从1970年1月1日上午12点开始的秒数。
# Import time module.
import time;
# Seconds
ticks = time.time()
print ("Number of ticks since 12:00am, January 1, 1970: ", ticks)
执行上面代码,得到以下结果 -
Number of ticks since 12:00am, January 1, 1970: 1497970093.6243818
但是,这个形式不能表示在时代(1970年1月1日上午12:00)之前的日期。在未来的日子也不能以这种方式表示 - 截止点是在2038年的UNIX和Windows的某个时刻。
2. 什么是TimeTuple?
许多Python时间函数将时间处理为9个数字的元组,如下所示:
| 索引 | 字段 | 值 |
|---|---|---|
| 0 | 4位数,表示年份 |
2018,2019… |
| 1 | 月份 | 1 ~ 12 |
| 2 | 日期 | 1 ~ 31 |
| 3 | 小时 | 0 ~ 23 |
| 4 | 分钟 | 0 ~ 59 |
| 5 | 秒 | 0 ~ 61(60或61是闰秒) |
| 6 | 星期几 | 0 ~ 6(0是星期一) |
| 7 | 一年的第几天 | 1 ~ 366(朱利安日) |
| 8 | 夏令时 | -1,0,1,-1表示库确定DST |
一个示例
import time
print (time.localtime());
这将产生如下结果:
time.struct_time(tm_year = 2016, tm_mon = 2, tm_mday = 15, tm_hour = 9,
tm_min = 29, tm_sec = 2, tm_wday = 0, tm_yday = 46, tm_isdst = 0)
上面的元组相当于struct_time结构。此结构具有以下属性 -
| 索引 | 字段 | 值 |
|---|---|---|
| 0 | tm_year | 2018,2019… |
| 1 | tm_mon | 1 ~ 12 |
| 2 | tm_mday | 1 ~ 31 |
| 3 | tm_hour | 0 ~ 23 |
| 4 | tm_min | 0 ~ 59 |
| 5 | tm_sec | 0 ~ 61(60或61是闰秒) |
| 6 | tm_wday | 0 ~ 6(0是星期一) |
| 7 | tm_yday | 1 ~ 366(朱利安日) |
| 8 | tm_isdst | -1,0,1,-1表示库确定DST |
能用图片说明白的尽量用图片说明 -

2.1.获取当前时间
要将从时间浮点值开始的秒数瞬间转换为时间序列,将浮点值传递给返回具有所有有效九个项目的时间元组的函数(例如本地时间)。
#!/usr/bin/python3
import time
localtime = time.localtime(time.time())
print ("Local current time :", localtime)
# 当前时间
curtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print (curtime)
执行上面代码,这将产生如下结果 -
Local current time : time.struct_time(tm_year=2017, tm_mon=6, tm_mday=20, tm_hour=23, tm_min=9, tm_sec=36, tm_wday=1, tm_yday=171, tm_isdst=0)
Curtime is => 2017-06-20 23:09:36
2.2.获取格式化时间
可以根据需要格式化任何时间,但也可使用可读格式获取时间的简单方法是 - asctime() -
#!/usr/bin/python3
import time
localtime = time.asctime( time.localtime(time.time()) )
print ("Local current time :", localtime)
执行上面代码,这将产生如下结果 -
Local current time : Mon Feb 15 10:32:13 2018
2.3.获取一个月的日历
calendar模块提供了广泛的方法来显示年历和月度日历。 在这里,将打印一个给定月份的日历(2021年11月) -
#!/usr/bin/python3
import calendar
cal = calendar.month(2021, 11)
print ("Here is the calendar:")
print (cal)
执行上面代码后,将输出以下结果 -
November 2021
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
3.时间模块
Python中有一个受欢迎的时间(time)模块,它提供了处理时间和表示之间转换的功能。以下是所有时间(time)可用方法的列表。
| 编号 | 方法 | 描述 |
|---|---|---|
| 1 | time.altzone | 本地DST时区的偏移量(以秒为单位的UTC),如果定义了有一个定义的话。 如果本地的DST时区是UTC的东部(如在西欧,包括英国),那么它是负数值。 |
| 2 | time.asctime([tupletime]) | 接受时间元组,并返回一个可读的24个字符的字符串,例如’Tue Dec 11 22:07:14 2019’。 |
| 3 | time.clock( ) | 将当前CPU时间返回为浮点数秒。 为了测量不同方法的计算成本,time.clock的值比time.time()的值更有用。 |
| 4 | time.ctime([secs]) | 类似于asctime(localtime(secs)),而没有参数就像asctime() |
| 5 | time.gmtime([secs]) | 接受从时代(epoch)以秒为单位的瞬间,并返回与UTC时间相关的时间元组t。 注 - t.tm_isdst始终为0 |
| 6 | time.localtime([secs]) | 接受从时代(epoch)以秒为单位的瞬间,并返回与本地时间相关的时间t(t.tm_isdst为0或1,具体取决于DST是否适用于本地规则的瞬时秒)。 |
| 7 | time.mktime(tupletime) | 接受在本地时间表示为时间元组的瞬间,并返回浮点值,该时间点以秒为单位表示。 |
| 8 | time.sleep(secs) | 暂停调用线程secs秒。 |
| 9 | time.strftime(fmt[,tupletime]) | 接受在本地时间表示为时间元组的瞬间,并返回一个表示由字符串fmt指定的时间的字符串。 |
| 10 | time.strptime(str,fmt = ‘%a %b %d %H:%M:%S %Y’)“) | 根据格式字符串fmt解析str,并返回时间元组格式的时间。 |
| 11 | time.time( ) | 返回当前时间时刻,即从时代(epoch)开始的浮点数秒数。 |
| 12 | time.tzset() | 重置库例程使用的时间转换规则。环境变量TZ指定如何完成。 |
时间(time)模块有两个重要的属性可用。它们是 -
| 编号 | 属性 | 描述 |
|---|---|---|
| 1 | time.timezone |
属性time.timezone是UTC和本地时区(不含DST)之间的偏移量(美洲为 > 0,欧洲,亚洲,非洲大部分地区为 0)。 |
| 2 | time.tzname |
属性time.tzname是一对与区域相关的字符串,它们分别是没有和具有DST的本地时区的名称。 |
4.日历模块
calendar模块提供与日历相关的功能,包括为给定的月份或年份打印文本日历的功能。
默认情况下,日历将星期一作为一周的第一天,将星期日作为最后一天。 如果想要更改这个,可调用calendar.setfirstweekday()函数设置修改。
以下是calendar模块可用的功能函数列表 -
| 编号 | 函数 | 描述 |
|---|---|---|
| 1 | calendar.calendar(year,w = 2,l = 1,c = 6) |
返回一个具有年份日历的多行字符串格式化为三列,以c个空格分隔。 w是每个日期的字符宽度; 每行的长度为21 * w + 18 + 2 * c,l是每周的行数。 |
| 2 | calendar.firstweekday( ) |
返回当前设置每周开始的星期。默认情况下,当日历首次导入时设置为:0,表示为星期一。 |
| 3 | calendar.isleap(year) |
如果给定年份(year)是闰年则返回True; 否则返回:False。 |
| 4 | calendar.leapdays(y1,y2) |
返回在范围(y1,y2)内的年份中的闰年总数。 |
| 5 | calendar.month(year,month,w = 2,l = 1) |
返回一个多行字符串,其中包含年份月份的日历,每周一行和两个标题行。 w是每个日期的字符宽度; 每行的长度为7 * w + 6。 l是每周的行数。 |
| 6 | calendar.monthcalendar(year,month) |
返回int类型的列表。每个子列表表示一个星期。年份月份以外的天数设置为0; 该月内的日期设定为月份的第几日:1 ~ 31。 |
| 7 | calendar.monthrange(year,month) |
返回两个整数。第一个是年度月(month)的星期几的代码; 第二个是当月的天数。表示星期几为0(星期一)至6(星期日); 月份是1到12。 |
| 8 | calendar.prcal(year,w = 2,l = 1,c = 6) |
类似于:calendar.calendar(year,w,l,c)的打印。 |
| 9 | calendar.prmonth(year,month,w = 2,l = 1) |
类似于:calendar.month(year,month,w,l)的打印。 |
| 10 | calendar.setfirstweekday(weekday) |
将每周的第一天设置为星期几的代码。 星期几的代码为0(星期一)至6(星期日)。 |
| 11 | calendar.timegm(tupletime) |
time.gmtime的倒数:以时间元组的形式接受时刻,并返回与从时代(epoch)开始的浮点数相同的时刻。 |
| 12 | calendar.weekday(year,month,day) |
返回给定日期的星期几的代码。星期几的代码为0(星期一)至6(星期日); 月数是1(1月)到12(12月)。 |
5.其他模块和功能
如果您有兴趣,那么可以在Python中找到其他重要的模块和功能列表,其中包含日期和时间。以下列出其它有用的模块 -
datetime模块pytz模块dateutil模块
