Python - 日期和时间
Python 程序可以通过多种方式处理日期和时间。在计算机中,日期格式之间的转换是一项常见的任务。Python 标准库中的以下模块负责处理日期和时间相关的操作 −
DateTime 模块
Time 模块
Calendar 模块
什么是 Tick Intervals
时间间隔是以秒为单位的浮点数。特定的时间点以自 1970 年 1 月 1 日 00:00(epoch)以来的秒数表示。
Python 中有一个常用的 time 模块,它提供了处理时间以及在不同表示形式之间转换的函数。函数 time.time() 返回自 1970 年 1 月 1 日 00:00(epoch)以来的当前系统时间(以 ticks 表示)。
示例
import time # 需要引入 time 模块
ticks = time.time()
print ("Number of ticks since 12:00am, January 1, 1970:", ticks)
这将产生类似以下的结果 −
Number of ticks since 12:00am, January 1, 1970: 1681928297.5316436
使用 ticks 进行日期运算非常简单。但是,epoch 之前的日期无法以这种形式表示。遥远未来的日期也无法以这种方式表示——UNIX 和 Windows 的截止点是在 2038 年的某个时间。
什么是 TimeTuple?
Python 的许多时间函数将时间处理为由 9 个数字组成的元组,如下所示 −
| Index | Field | Values |
|---|---|---|
| 0 | 4-digit year | 2016 |
| 1 | Month | 1 to 12 |
| 2 | Day | 1 to 31 |
| 3 | Hour | 0 to 23 |
| 4 | Minute | 0 to 59 |
| 5 | Second | 0 to 61 (60 or 61 are leap-seconds) |
| 6 | Day of Week | 0 to 6 (0 is Monday) |
| 7 | Day of year | 1 to 366 (Julian day) |
| 8 | Daylight savings | -1, 0, 1, -1 means library determines DST |
例如,
>>>import time >>> print (time.localtime())
这将产生以下 输出 −
time.struct_time(tm_year=2023, tm_mon=4, tm_mday=19, tm_hour=23, tm_min=49, tm_sec=8, tm_wday=2, tm_yday=109, tm_isdst=0)
上述元组等同于 struct_time 结构。该结构具有以下属性 −
| Index | Attributes | Values |
|---|---|---|
| 0 | tm_year | 2016 |
| 1 | tm_mon | 1 to 12 |
| 2 | tm_mday | 1 to 31 |
| 3 | tm_hour | 0 to 23 |
| 4 | tm_min | 0 to 59 |
| 5 | tm_sec | 0 to 61 (60 or 61 are leap-seconds) |
| 6 | tm_wday | 0 to 6 (0 is Monday) |
| 7 | tm_yday | 1 to 366 (Julian day) |
| 8 | tm_isdst | -1, 0, 1, -1 means library determines DST |
获取当前时间
要将自 epoch 以来的 秒 浮点值转换为时间元组,可以将该浮点值传递给一个函数(例如 localtime),该函数会返回包含所有有效九个项目的 time-tuple。
import time
localtime = time.localtime(time.time())
print ("Local current time :", localtime)
这将产生以下结果,可以格式化为任何其他可呈现的形式 −
Local current time : time.struct_time(tm_year=2023, tm_mon=4, tm_mday=19, tm_hour=23, tm_min=42, tm_sec=41, tm_wday=2, tm_yday=109, tm_isdst=0)
获取格式化时间
您可以根据需要格式化任何时间,但获取可读格式时间的一个简单方法是使用 asctime() −
import time
localtime = time.asctime( time.localtime(time.time()) )
print ("Local current time :", localtime)
这将产生以下 输出 −
Local current time : Wed Apr 19 23:45:27 2023
获取月份日历
calendar 模块提供了多种方法来处理年度和月度日历。这里,我们打印给定月份(2008 年 1 月)的日历。
import calendar
cal = calendar.month(2023, 4)
print ("Here is the calendar:")
print (cal)
这将产生以下 输出 −
Here is the calendar:
April 2023
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
time 模块
Python 中有一个流行的 time 模块,它提供了处理时间和在不同表示形式之间转换的函数。以下是所有可用方法的列表。
| 序号 | 函数及其描述 |
|---|---|
| 1 | time.altzone
本地 DST 时区的偏移量,以 UTC 以西的秒数表示,如果定义了的话。如果本地 DST 时区位于 UTC 以东(如西欧,包括英国),则此值为负。只有在 daylight 非零时才使用此值。 |
| 2 | time.asctime([tupletime])
接受一个 time-tuple 并返回一个可读的 24 字符字符串,例如 'Tue Dec 11 18:07:14 2008'。 |
| 3 | time.clock( )
返回当前 CPU 时间,以浮点数的秒数表示。要测量不同方法的计算成本,time.clock 的值比 time.time() 的值更有用。 |
| 4 | time.ctime([secs])
类似于 asctime(localtime(secs)),不带参数时类似于 asctime( ) |
| 5 | time.gmtime([secs])
接受自 epoch 以来的秒数表示的瞬间,并返回带有 UTC 时间的 time-tuple t。注意:t.tm_isdst 始终为 0 |
| 6 | time.localtime([secs])
接受自 epoch 以来的秒数表示的瞬间,并返回带有本地时间的 time-tuple t(t.tm_isdst 为 0 或 1,取决于本地规则是否对瞬间 secs 应用 DST)。 |
| 7 | time.mktime(tupletime)
接受以本地时间表示的 time-tuple,并返回自 epoch 以来的秒数表示的浮点值。 |
| 8 | time.sleep(secs)
暂停调用线程 secs 秒。 |
| 9 | time.strftime(fmt[,tupletime])
接受以本地时间表示的 time-tuple,并返回由字符串 fmt 指定的瞬间的字符串表示。 |
| 10 | time.strptime(str,fmt='%a %b %d %H:%M:%S %Y')
根据格式字符串 fmt 解析 str,并返回 time-tuple 格式的瞬间。 |
| 11 | time.time( )
返回当前时间瞬间,自 epoch 以来的浮点秒数。 |
| 12 | time.tzset()
重置库例程使用的时区转换规则。环境变量 TZ 指定了如何执行此操作。 |
让我们简要介绍这些函数。
time 模块有两个重要的属性,它们是 −
| 序号 | 属性及其描述 |
|---|---|
| 1 | time.timezone 属性 time.timezone 是本地时区(不含 DST)相对于 UTC 的秒偏移量(美洲为 >0;欧洲、亚洲、非洲大部分地区为 <=0)。 |
| 2 | time.tzname 属性 time.tzname 是一对依赖于 locale 的字符串,分别是本地时区不含 DST 和包含 DST 时的名称。 |
calendar 模块
calendar 模块提供了与日历相关的函数,包括打印给定月份或年份的文本日历的函数。
默认情况下,calendar 将周一视为一周的第一天,周日视为最后一天。要更改此设置,请调用 calendar.setfirstweekday() 函数。
以下是 calendar 模块中可用的函数列表 −
| 序号 | 函数及描述 |
|---|---|
| 1 | calendar.calendar() 返回一个多行字符串,包含 year 年份的日历,格式化为三列,由 c 个空格分隔。w 是每个日期的字符宽度;每行长度为 21*w+18+2*c。l 是每周的行数。 |
| 2 | calendar.firstweekday() 返回每周开始的 weekday 的当前设置。默认情况下,首次导入 calendar 时,此值为 0,表示周一。 |
| 3 | calendar.isleap() 如果 year 是闰年则返回 True;否则返回 False。 |
| 4 | calendar.leapdays() 返回 range(y1,y2) 范围内年份中的闰日总数。 |
| 5 | calendar.month() 返回一个多行字符串,包含 year 年份 month 月份的日历,每周一行加上两行标题。w 是每个日期的字符宽度;每行长度为 7*w+6。l 是每周的行数。 |
| 6 | calendar.monthcalendar() 返回一个整数列表的列表。每个子列表表示一周。year 年份 month 月份之外的天数设置为 0;月份内的天数设置为其日期,从 1 开始。 |
| 7 | calendar.monthrange() 返回两个整数。第一个是 year 年份 month 月份第一天的 weekday 代码;第二个是该月的天数。Weekday 代码为 0(周一)到 6(周日);月份编号为 1 到 12。 |
| 8 | calendar.prcal() 相当于 print calendar.calendar(year,w,l,c)。 |
| 9 | calendar.prmonth() 相当于 print calendar.month(year,month,w,l)。 |
| 10 | calendar.setfirstweekday() 将每周的第一天设置为 weekday 代码 weekday。Weekday 代码为 0(周一)到 6(周日)。 |
| 11 | calendar.timegm() time.gmtime 的逆函数:接受 time-tuple 形式的时间瞬间,并返回从 epoch 开始的浮点秒数表示的相同瞬间。 |
| 12 | calendar.weekday() 返回给定日期的 weekday 代码。Weekday 代码为 0(周一)到 6(周日);月份编号为 1(一月)到 12(十二月)。 |
Python datetime 模块
Python 的 datetime 模块包含在标准库中。它由帮助操作日期和时间数据并执行日期时间算术的 class 组成。
datetime class 的对象要么是 aware(带时区信息),要么是 naive(不带时区信息)。如果对象包含时区信息,则为 aware;否则分类为 naive。date class 的对象是 naive,而 time 和 datetime 对象是 aware。
Python date 对象
date 对象表示包含年、月、日的一个日期。当前的公历向两个方向无限延伸。
语法
datetime.date(year, month, day)
参数必须是整数,且在以下范围内 −
year − MINYEAR <= year <= MAXYEAR
month − 1 <= month <= 12
day − 1 <= day <= 给定月份和年份的天数
如果任何参数的值超出这些范围,将引发 ValueError。
示例
from datetime import date
date1 = date(2023, 4, 19)
print("Date:", date1)
date2 = date(2023, 4, 31)
它将产生以下输出 −
Date: 2023-04-19 Traceback (most recent call last): File "C:\Python311\hello.py", line 8, in <module> date2 = date(2023, 4, 31) ValueError: day is out of range for month
date 类属性
date.min − 可表示的最早日期,即 date(MINYEAR, 1, 1)。
date.max − 可表示的最晚日期,即 date(MAXYEAR, 12, 31)。
date.resolution − 非相等 date 对象之间可能的最小差异。
date.year − 包含 MINYEAR 和 MAXYEAR 之间。
date.month − 包含 1 到 12 之间。
date.day − 包含 1 到给定年份给定月份的天数之间。
示例
from datetime import date
# 获取最小日期
mindate = date.min
print("Minimum Date:", mindate)
# 获取最大日期
maxdate = date.max
print("Maximum Date:", maxdate)
Date1 = date(2023, 4, 20)
print("Year:", Date1.year)
print("Month:", Date1.month)
print("Day:", Date1.day)
它将产生以下输出 −
Minimum Date: 0001-01-01 Maximum Date: 9999-12-31 Year: 2023 Month: 4 Day: 20
Date 类中的类方法
today() − 返回当前本地日期。
fromtimestamp(timestamp) − 返回对应于 POSIX timestamp 的本地日期,例如 time.time() 返回的值。
fromordinal(ordinal) − 返回对应于 proleptic Gregorian ordinal 的日期,其中 1 年的 1 月 1 日的 ordinal 为 1。
fromisoformat(date_string) − 返回对应于以任何有效 ISO 8601 格式给定的 date_string 的日期,但不包括 ordinal 日期。
示例
from datetime import date
print (date.today())
d1=date.fromisoformat('2023-04-20')
print (d1)
d2=date.fromisoformat('20230420')
print (d2)
d3=date.fromisoformat('2023-W16-4')
print (d3)
它将产生以下输出 −
2023-04-20 2023-04-20 2023-04-20 2023-04-20
Date 类中的实例方法
replace() − 通过关键字参数指定的新值替换指定的属性,返回一个新的日期。
timetuple() − 返回类似 time.localtime() 返回的 time.struct_time。
toordinal() − 返回日期的 proleptic Gregorian ordinal,其中 1 年的 1 月 1 日的 ordinal 为 1。对于任何 date 对象 d,date.fromordinal(d.toordinal()) == d。
weekday() − 以整数形式返回星期几,其中周一为 0,周日为 6。
isoweekday() − 以整数形式返回星期几,其中周一为 1,周日为 7。
isocalendar() − 返回一个包含三个组件的命名元组对象:year、week 和 weekday。
isoformat() − 返回以 ISO 8601 格式表示的日期字符串,格式为 YYYY-MM-DD:
__str__() − 对于日期 d,str(d) 等同于 d.isoformat()。
ctime() − 返回表示日期的字符串:
strftime(format) − 返回由显式格式字符串控制的表示日期的字符串。
__format__(format) − 与 date.strftime() 相同。
示例
from datetime import date
d = date.fromordinal(738630) # 0001年1月1日之后的第738630天
print (d)
print (d.timetuple())
# 与格式化字符串输出相关的函数
print (d.isoformat())
print (d.strftime("%d/%m/%y"))
print (d.strftime("%A %d. %B %Y"))
print (d.ctime())
print ('The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month"))
# 用于提取不同历法下“组件”的方法
t = d.timetuple()
for i in t:
print(i)
ic = d.isocalendar()
for i in ic:
print(i)
# date 对象是不可变的;所有操作都会产生新对象
print (d.replace(month=5))
它将产生以下输出 −
2023-04-20 time.struct_time(tm_year=2023, tm_mon=4, tm_mday=20, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=110, tm_isdst=-1) 2023-04-20 20/04/23 Thursday 20. April 2023 Thu Apr 20 00:00:00 2023 The day is 20, the month is April. 2023 4 20 0 0 0 3 110 -1 2023 16 4 2023-05-20
Python time 模块
time 类对象表示一天中的本地时间。它独立于任何特定日期。如果该对象包含 tzinfo 细节,则它是 aware 对象。如果为 None,则 time 对象是 naive 对象。
语法
datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
所有参数都是可选的。tzinfo 可以是 None,或 tzinfo 子类的实例。其余参数必须是以下范围内的整数 −
hour − 0 <= hour < 24,
minute − 0 <= minute < 60,
second − 0 <= second < 60,
microsecond − 0 <= microsecond < 1000000
如果任何参数超出这些范围,将引发 ValueError。
示例
from datetime import time
time1 = time(8, 14, 36)
print("Time:", time1)
time2 = time(minute = 12)
print("time", time2)
time3 = time()
print("time", time3)
time4 = time(hour = 26)
它将产生以下输出 −
Time: 08:14:36 time 00:12:00 time 00:00:00 Traceback (most recent call last): File "/home/cg/root/64b912f27faef/main.py", line 12, intime4 = time(hour = 26) ValueError: hour must be in 0..23
类属性
time.min − 可表示的最早时间,time(0, 0, 0, 0)。
time.max − 可表示的最晚时间,time(23, 59, 59, 999999)。
time.resolution − 非相等 time 对象之间可能的最小差异。
示例
from datetime import time print(time.min) print(time.max) print (time.resolution)
它将产生以下输出 −
00:00:00 23:59:59.999999 0:00:00.000001
实例属性
time.hour − 在 range(24) 范围内
time.minute − 在 range(60) 范围内
time.second − 在 range(60) 范围内
time.microsecond − 在 range(1000000) 范围内
time.tzinfo − time 构造函数的 tzinfo 参数,或 None。
示例
from datetime import time t = time(8,23,45,5000) print(t.hour) print(t.minute) print (t.second) print (t.microsecond)
它将产生以下输出 −
8 23 455000
time 对象的实例方法
replace() − 返回一个具有相同值的时间,但通过指定的关键字参数为给定的属性赋予新值。
isoformat() − 返回以 ISO 8601 格式表示时间的字符串
__str__() − 对于时间 t,str(t) 等同于 t.isoformat()。
strftime(format) − 返回由显式格式字符串控制的表示时间的字符串。
__format__(format) − 与 time.strftime() 相同。
utcoffset() − 如果 tzinfo 是 None,返回 None,否则返回 self.tzinfo.utcoffset(None),
dst() − 如果 tzinfo 是 None,返回 None,否则返回 self.tzinfo.dst(None),
tzname() − 如果 tzinfo 是 None,返回 None,否则返回 self.tzinfo.tzname(None),或引发异常
Python datetime 对象
datetime class 的对象包含了日期和时间的信息。它假设使用当前向两方向无限延伸的公历;类似于 time 对象,每天正好有 3600*24 秒。
语法
datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
year、month 和 day 参数是必需的。
year − MINYEAR <= year <= MAXYEAR,
month − 1 <= month <= 12,
day − 1 <= day <= 给定月份和年份的天数,
hour − 0 <= hour < 24,
minute − 0 <= minute < 60,
second −0 <= second < 60,
microsecond − 0 <= microsecond < 1000000,
fold − in [0, 1]。
如果给出任何超出范围的参数,将引发 ValueError。
示例
from datetime import datetime dt = datetime(2023, 4, 20) print(dt) dt = datetime(2023, 4, 20, 11, 6, 32, 5000) print(dt)
它将产生以下输出 −
2023-04-20 00:00:00 2023-04-20 11:06:32.005000
类属性
datetime.min − 可表示的最早 datetime,datetime(MINYEAR, 1, 1, tzinfo=None)。
datetime.max − 可表示的最晚 datetime,datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, tzinfo=None)。
datetime.resolution − 不相等 datetime 对象之间可能的最小差异,timedelta(microseconds=1)。
示例
from datetime import datetime
min = datetime.min
print("Min DateTime ", min)
max = datetime.max
print("Max DateTime ", max)
它将产生以下输出 −
Min DateTime 0001-01-01 00:00:00 Max DateTime 9999-12-31 23:59:59.999999
datetime 对象的实例属性
datetime.year − 包含 MINYEAR 和 MAXYEAR 之间。
datetime.month − 包含 1 到 12 之间。
datetime.day − 1 到给定年份给定月份的天数之间。
datetime.hour − 在 range(24) 内。
datetime.minute − 在 range(60) 内。
datetime.second − 在 range(60) 内。
datetime.microsecond − 在 range(1000000) 内。
datetime.tzinfo − 传递给 datetime 构造函数的 tzinfo 参数的对象,如果未传递则为 None。
datetime.fold − 在 [0, 1] 内。用于消除重复时间间隔期间的墙钟时间的歧义。
示例
from datetime import datetime
dt = datetime.now()
print("Day: ", dt.day)
print("Month: ", dt.month)
print("Year: ", dt.year)
print("Hour: ", dt.hour)
print("Minute: ", dt.minute)
print("Second: ", dt.second)
它将产生以下输出 −
Day: 20 Month: 4 Year: 2023 Hour: 15 Minute: 5 Second: 52
datetime 对象的类方法
today() − 返回当前本地 datetime,tzinfo 为 None。
now(tz=None) − 返回当前本地日期和时间。
utcnow() − 返回当前 UTC 日期和时间,tzinfo 为 None。
utcfromtimestamp(timestamp) − 返回对应 POSIX timestamp 的 UTC datetime,tzinfo 为 None。
fromtimestamp(timestamp, timezone.utc) − 在 POSIX 兼容平台上,相当于 datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp)。
fromordinal(ordinal) − 返回对应 proleptic Gregorian ordinal 的 datetime,其中 1 年的 1 月 1 日的 ordinal 为 1。
fromisoformat(date_string) − 返回对应任何有效 ISO 8601 格式的 date_string 的 datetime。
datetime 对象的实例方法
date() − 返回具有相同 year、month 和 day 的 date 对象。
time() − 返回具有相同 hour、minute、second、microsecond 和 fold 的 time 对象。
timetz() − 返回具有相同 hour、minute、second、microsecond、fold 和 tzinfo 属性的 time 对象。另见方法 time()。
replace() − 返回具有相同属性的 datetime,除了通过指定关键字参数赋予新值的那些属性。
astimezone(tz=None) − 返回具有新 tzinfo 属性 tz 的 datetime 对象。
utcoffset() − 如果 tzinfo 为 None,返回 None,否则返回 self.tzinfo.utcoffset(self)。
dst() − 如果 tzinfo 为 None,返回 None,否则返回 self.tzinfo.dst(self)。
tzname() − 如果 tzinfo 为 None,返回 None,否则返回 self.tzinfo.tzname(self)。
timetuple() − 返回类似 time.localtime() 返回的 time.struct_time。
atetime.toordinal() − 返回日期的 proleptic Gregorian ordinal。
timestamp() − 返回对应 datetime 实例的 POSIX timestamp。
isoweekday() − 返回一周中的星期几作为整数,其中星期一为 1,星期日为 7。
isocalendar() − 返回一个包含三个组件的命名元组:year、week 和 weekday。
isoformat(sep='T', timespec='auto') − 返回以 ISO 8601 格式表示日期和时间的字符串。
__str__() − 对于 datetime 实例 d,str(d) 等同于 d.isoformat(' ')。
ctime() − 返回表示日期和时间的字符串:
strftime(format) − 返回由显式格式字符串控制的表示日期和时间的字符串。
__format__(format) − 与 strftime() 相同。
示例
from datetime import datetime, date, time, timezone
# 使用 datetime.combine()
d = date(2022, 4, 20)
t = time(12, 30)
datetime.combine(d, t)
# 使用 datetime.now()
d = datetime.now()
print (d)
# 使用 datetime.strptime()
dt = datetime.strptime("23/04/20 16:30", "%d/%m/%y %H:%M")
# 使用 datetime.timetuple() 获取所有属性的元组
tt = dt.timetuple()
for it in tt:
print(it)
# ISO 格式的日期
ic = dt.isocalendar()
for it in ic:
print(it)
它将产生以下输出 −
2023-04-20 15:12:49.816343 2020 4 23 16 30 0 3 114 -1 2020 17 4
Python timedelta 对象
timedelta 对象表示两个日期或两个时间对象之间的持续时间。
语法
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
内部,属性以 days、seconds 和 microseconds 存储。其他参数会被转换为这些单位 −
1 毫秒转换为 1000 微秒。
1 分钟转换为 60 秒。
1 小时转换为 3600 秒。
1 周转换为 7 天。
然后,days、seconds 和 microseconds 会被规范化,以确保表示的唯一性。
示例
以下示例显示 Python 内部仅存储 days、seconds 和 microseconds。
from datetime import timedelta delta = timedelta( days=100, seconds=27, microseconds=10, milliseconds=29000, minutes=5, hours=12, weeks=2 ) # 仅保留 days、seconds 和 microseconds print (delta)
它将产生以下输出 −
114 days, 12:05:56.000010
示例
以下示例展示如何将 timedelta 对象添加到 datetime 对象。
from datetime import datetime, timedelta
date1 = datetime.now()
date2= date1+timedelta(days = 4)
print("Date after 4 days:", date2)
date3 = date1-timedelta(15)
print("Date before 15 days:", date3)
它将产生以下输出 −
Date after 4 days: 2023-04-24 18:05:39.509905 Date before 15 days: 2023-04-05 18:05:39.509905
timedelta 对象的类属性
timedelta.min − 最小的 timedelta 对象,即 timedelta(-999999999)。
timedelta.max − 最大的 timedelta 对象,即 timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999)。
timedelta.resolution − 非相等 timedelta 对象之间可能的最小差异,即 timedelta(microseconds=1)
示例
from datetime import timedelta
# 获取最小值
min = timedelta.min
print("Minimum value:", min)
max = timedelta.max
print("Maximum value", max)
它将产生以下输出 −
Minimum value: -999999999 days, 0:00:00 Maximum value 999999999 days, 23:59:59.999999
timedelta 对象的实例属性
由于内部仅存储 day、second 和 microseconds,因此这些是 timedelta 对象的唯一实例属性。
days − 包含 -999999999 到 999999999 之间
seconds − 包含 0 到 86399 之间
microseconds − 包含 0 到 999999 之间
timedelta 对象的实例方法
timedelta.total_seconds() − 返回持续时间内包含的总秒数。
示例
from datetime import timedelta year = timedelta(days=365) years = 5 * year print (years) print (years.days // 365) 646 year_1 = years // 5 print(year_1.days)
它将产生以下输出 −
1825 days, 0:00:00 5 365