Python 简明教程
Python - Date and Time
Python 程序可以使用多种方法处理日期和时间。在日期格式之间转换是计算机的常见任务。Python 标准库中的以下模块处理日期和时间相关的处理 −
A Python program can handle date and time in several ways. Converting between date formats is a common chore for computers. Following modules in Python’s standard library handle date and time related processing −
-
DateTime module
-
Time module
-
Calendar module
What are Tick Intervals
时间间隔是秒为单位的浮点数字。特定时间点以 1970 年 1 月 1 日上午 12:00(历元)以来的秒数表示。
Time intervals are floating-point numbers in units of seconds. Particular instants in time are expressed in seconds since 12:00am, January 1, 1970(epoch).
Python 中有一个流行的 time 模块,它提供用于处理时间和在不同表示之间转换的函数。函数 time.time() 返回自 1970 年 1 月 1 日上午 12:00(历元)以来的当前系统时间(按刻度)。
There is a popular time module available in Python, which provides functions for working with times, and for converting between representations. The function time.time() returns the current system time in ticks since 12:00am, January 1, 1970(epoch).
Example
import time # This is required to include time module.
ticks = time.time()
print ("Number of ticks since 12:00am, January 1, 1970:", ticks)
结果类似于以下内容:
This would produce a result something as follows −
Number of ticks since 12:00am, January 1, 1970: 1681928297.5316436
刻度可以轻松做日期计算。但是,无法以这种形式表示历元之前的日期。遥远未来的日期也不能以这种方式表示 - UNIX 和 Windows 的截止时间是 2038 年的某个时间。
Date arithmetic is easy to do with ticks. However, dates before the epoch cannot be represented in this form. Dates in the far future also cannot be represented this way - the cutoff point is sometime in 2038 for UNIX and Windows.
What is TimeTuple?
Python 的许多时间函数将时间作为 9 个数字的元组进行处理,如下所示:
Many of the Python’s time functions handle time as a tuple of 9 numbers, as shown below −
For example,
For example,
>>>import time
>>> print (time.localtime())
这将产生一个 output ,如下所示:
This would produce an output as follows −
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 结构。此结构具有以下属性:
The above tuple is equivalent to struct_time structure. This structure has the following attributes −
Getting the Current Time
要将自历元起的 seconds 浮点值的时间点转换为时间元组,将浮点值传递给返回包含所有 9 个有效项的时间元组的函数(例如,localtime)。
To translate a time instant from seconds since the epoch floating-point value into a time-tuple, pass the floating-point value to a function (e.g., localtime) that returns a time-tuple with all valid nine items.
import time
localtime = time.localtime(time.time())
print ("Local current time :", localtime)
这将产生以下结果,该结果可以用任何其他可表示形式进行格式化:
This would produce the following result, which could be formatted in any other presentable form −
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)
Getting the Formatted Time
您可以根据需要对任何时间进行格式化,但以可读格式获取时间的简单方法是 asctime() :
You can format any time as per your requirement, but a simple method to get time in a readable format is asctime() −
import time
localtime = time.asctime( time.localtime(time.time()) )
print ("Local current time :", localtime)
这将产生以下 output −
This would produce the following output −
Local current time : Wed Apr 19 23:45:27 2023
Getting the Calendar for a Month
日历模块提供了多种方法来使用年历和月历。这里,我们为给定的月份(2008 年 1 月)打印日历。
The calendar module gives a wide range of methods to play with yearly and monthly calendars. Here, we print a calendar for a given month (Jan 2008).
import calendar
cal = calendar.month(2023, 4)
print ("Here is the calendar:")
print (cal)
这将产生以下 output −
This would produce the following output −
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
The time Module
Python 中有一个流行的 time 模块,它提供用于处理时间和在不同表示之间转换的函数。以下是所有可用方法的列表。
There is a popular time module available in Python, which provides functions for working with times and for converting between representations. Here is the list of all available methods.
让我们简单浏览一下这些函数。
Let us go through the functions briefly.
时间模块提供两个重要的属性。它们是:
There are two important attributes available with time module. They are −
The calendar Module
日历模块提供与日历相关的一些功能,包括打印给定月份或年份文字日历的功能。
The calendar module supplies calendar-related functions, including functions to print a text calendar for a given month or year.
默认情况下,日历将星期一作为一周的第一天,将星期日作为最后一天。要更改此设置,请调用 calendar.setfirstweekday() 函数。
By default, calendar takes Monday as the first day of the week and Sunday as the last one. To change this, call the calendar.setfirstweekday() function.
以下列出了 calendar 模块提供的函数:
Here is a list of functions available with the calendar module −
Python datetime Module
Python 的 datetime 模块包含在标准库中。它包含用于帮助处理数据和时间数据以及执行日期时间运算的类。
Python’s datetime module is included in the standard library. It consists of classes that help manipulate data and time data and perform date time arithmetic.
datetime 类的对象要么是感知时间的,要么是幼稚的。如果对象包含时区信息,则它是感知时间的;否则,它被归类为幼稚的。date 类的对象是幼稚的,而 time 和 datetime 对象是感知时间的。
Objects of datetime classes are either aware or naïve. If the object includes timezone information it is aware, and if not it is classified as naïve. An object of date class is naïve, whereas time and datetime objects are aware.
Python date Object
日期对象用年、月和日表示日期。当前的格里高利历在两个方向上无限延伸。
A date object represents a date with year, month, and day. The current Gregorian calendar is indefinitely extended in both directions.
Syntax
datetime.date(year, month, day)
参数必须是整数,在以下范围内:
Arguments must be integers, in the following ranges −
-
year − MINYEAR ⇐ year ⇐ MAXYEAR
-
month − 1 ⇐ month ⇐ 12
-
day − 1 ⇐ day ⇐ number of days in the given month and year
如果给出了超出这些范围的任何参数的值,则会引发 ValueError。
If the value of any argument outside those ranges is given, ValueError is raised.
Example
from datetime import date
date1 = date(2023, 4, 19)
print("Date:", date1)
date2 = date(2023, 4, 31)
它将生成以下 output −
It will produce the following output −
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 class attributes
-
date.min − The earliest representable date, date(MINYEAR, 1, 1).
-
date.max − The latest representable date, date(MAXYEAR, 12, 31).
-
date.resolution − The smallest possible difference between non-equal date objects.
-
date.year − Between MINYEAR and MAXYEAR inclusive.
-
date.month − Between 1 and 12 inclusive.
-
date.day − Between 1 and the number of days in the given month of the given year.
Example
from datetime import date
# Getting min date
mindate = date.min
print("Minimum Date:", mindate)
# Getting max date
maxdate = date.max
print("Maximum Date:", maxdate)
Date1 = date(2023, 4, 20)
print("Year:", Date1.year)
print("Month:", Date1.month)
print("Day:", Date1.day)
它将生成以下 output −
It will produce the following output −
Minimum Date: 0001-01-01
Maximum Date: 9999-12-31
Year: 2023
Month: 4
Day: 20
Class Methods in Date Class
-
today() − Return the current local date.
-
fromtimestamp(timestamp) − Return the local date corresponding to the POSIX timestamp, such as is returned by time.time().
-
fromordinal(ordinal) − Return the date corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1.
-
fromisoformat(date_string) − Return a date corresponding to a date_string given in any valid ISO 8601 format, except ordinal dates
Example
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)
它将生成以下 output −
It will produce the following output −
2023-04-20
2023-04-20
2023-04-20
2023-04-20
Instance Methods in Date Class
-
replace() − Return a date by replacing specified attributes with new values by keyword arguments are specified.
-
timetuple() − Return a time.struct_time such as returned by time.localtime().
-
toordinal() − Return the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1. For any date object d, date.fromordinal(d.toordinal()) == d.
-
weekday() − Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
-
isoweekday() − Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
-
isocalendar() − Return a named tuple object with three components: year, week and weekday.
-
isoformat() − Return a string representing the date in ISO 8601 format, YYYY-MM-DD:
-
str() − For a date d, str(d) is equivalent to d.isoformat()
-
ctime() − Return a string representing the date:
-
strftime(format) − Return a string representing the date, controlled by an explicit format string.
-
format(format) − Same as date.strftime().
Example
from datetime import date
d = date.fromordinal(738630) # 738630th day after 1. 1. 0001
print (d)
print (d.timetuple())
# Methods related to formatting string output
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"))
# Methods for to extracting 'components' under different calendars
t = d.timetuple()
for i in t:
print(i)
ic = d.isocalendar()
for i in ic:
print(i)
# A date object is immutable; all operations produce a new object
print (d.replace(month=5))
它将生成以下 output −
It will produce the following output −
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 Module
一个对象 time 类表示这个一天中的本地时间。它独立于任何特定的一天。如果对象包含 tzinfo 详情,它就是一个有意识的对象。如果它为 None,则时间对象是一个天真的对象。
An object time class represents the local time of the day. It is independent of any particular day. It the object contains the tzinfo details, it is the aware object. If it is None then the time object is the naive object.
Syntax
datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
所有参数都是可选的。tzinfo 为 None,或为 tzinfo 子类的实例。剩余参数必须是在以下范围内的整数 −
All arguments are optional. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments must be integers in the following ranges −
-
hour − 0 ⇐ hour < 24,
-
minute − 0 ⇐ minute < 60,
-
second − 0 ⇐ second < 60,
-
microsecond − 0 ⇐ microsecond < 1000000
如果任何参数超出这些范围,则引发 ValueError。
If any of the arguments are outside those ranges is given, ValueError is raised.
Example
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)
它将生成以下 output −
It will produce the following output −
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, in
time4 = time(hour = 26)
ValueError: hour must be in 0..23
Class attributes
-
time.min − The earliest representable time, time(0, 0, 0, 0).
-
time.max − The latest representable time, time(23, 59, 59, 999999).
-
time.resolution − The smallest possible difference between non-equal time objects.
Example
from datetime import time
print(time.min)
print(time.max)
print (time.resolution)
它将生成以下 output −
It will produce the following output −
00:00:00
23:59:59.999999
0:00:00.000001
Instance attributes
-
time.hour − In range(24)
-
time.minute − In range(60)
-
time.second − In range(60)
-
time.microsecond − In range(1000000)
-
time.tzinfo − the tzinfo argument to the time constructor, or None.
Example
from datetime import time
t = time(8,23,45,5000)
print(t.hour)
print(t.minute)
print (t.second)
print (t.microsecond)
它将生成以下 output −
It will produce the following output −
8
23
455000
Instance Methods of time Object
-
replace() − Return a time with the same value, except for those attributes given new values by whichever keyword arguments are specified.
-
isoformat() − Return a string representing the time in ISO 8601 format
-
str() − For a time t, str(t) is equivalent to t.isoformat().
-
strftime(format) − Return a string representing the time, controlled by an explicit format string.
-
format(format) − Same as time.strftime().
-
utcoffset() − If tzinfo is None, returns None, else returns self.tzinfo.utcoffset(None),
-
dst() − If tzinfo is None, returns None, else returns self.tzinfo.dst(None),
-
tzname() − If tzinfo is None, returns None, else returns self.tzinfo.tzname(None), or raises an exception
Python datetime object
datetime 类的一个对象包含着日期和时间的全部信息。它假设当前的公历在两个方向上延伸,就像一个 time 对象,并且每天精确包含 3600*24 秒。
An object of datetime class contains the information of date and time together. It assumes the current Gregorian calendar extended in both directions; like a time object, and there are exactly 3600*24 seconds in every day.
Syntax
datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
year、month 和 day 参数是必需的。
The year, month and day arguments are required.
-
year − MINYEAR ⇐ year ⇐ MAXYEAR,
-
month − 1 ⇐ month ⇐ 12,
-
day − 1 ⇐ day ⇐ number of days in the given month and year,
-
hour − 0 ⇐ hour < 24,
-
minute − 0 ⇐ minute < 60,
-
second −0 ⇐ second < 60,
-
microsecond − 0 ⇐ microsecond < 1000000,
-
fold − in [0, 1].
如果给出了任何超出范围的参数,则引发 ValueError。
If any argument in outside ranges is given, ValueError is raised.
Example
from datetime import datetime
dt = datetime(2023, 4, 20)
print(dt)
dt = datetime(2023, 4, 20, 11, 6, 32, 5000)
print(dt)
它将生成以下 output −
It will produce the following output −
2023-04-20 00:00:00
2023-04-20 11:06:32.005000
Class attributes
-
datetime.min − The earliest representable datetime, datetime(MINYEAR, 1, 1, tzinfo=None).
-
datetime.max − The latest representable datetime, datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, tzinfo=None).
-
datetime.resolution − The smallest possible difference between non-equal datetime objects, timedelta(microseconds=1).
Example
from datetime import datetime
min = datetime.min
print("Min DateTime ", min)
max = datetime.max
print("Max DateTime ", max)
它将生成以下 output −
It will produce the following output −
Min DateTime 0001-01-01 00:00:00
Max DateTime 9999-12-31 23:59:59.999999
Instance Attributes of datetime Object
-
datetime.year − Between MINYEAR and MAXYEAR inclusive.
-
datetime.month − Between 1 and 12 inclusive.
-
datetime.day − Between 1 and the number of days in the given month of the given year.
-
datetime.hour − In range(24)
-
datetime.minute − In range(60)
-
datetime.second − In range(60)
-
datetime.microsecond − In range(1000000).
-
datetime.tzinfo − The object passed as the tzinfo argument to the datetime constructor, or None if none was passed.
-
datetime.fold − In [0, 1]. Used to disambiguate wall times during a repeated interval.
Example
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)
它将生成以下 output −
It will produce the following output −
Day: 20
Month: 4
Year: 2023
Hour: 15
Minute: 5
Second: 52
Class Methods of datetime Object
-
today() − Return the current local datetime, with tzinfo None.
-
now(tz=None) − Return the current local date and time.
-
utcnow() − Return the current UTC date and time, with tzinfo None.
-
utcfromtimestamp(timestamp) − Return the UTC datetime corresponding to the POSIX timestamp, with tzinfo None
-
fromtimestamp(timestamp, timezone.utc) − On the POSIX compliant platforms, it is equivalent todatetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp)
-
fromordinal(ordinal) − Return the datetime corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1.
-
fromisoformat(date_string) − Return a datetime corresponding to a date_string in any valid ISO 8601 format.
Instance Methods of datetime Object
-
date() − Return date object with same year, month and day.
-
time() − Return time object with same hour, minute, second, microsecond and fold.
-
timetz() − Return time object with same hour, minute, second, microsecond, fold, and tzinfo attributes. See also method time().
-
replace() − Return a datetime with the same attributes, except for those attributes given new values by whichever keyword arguments are specified.
-
astimezone(tz=None) − Return a datetime object with new tzinfo attribute tz
-
utcoffset() − If tzinfo is None, returns None, else returns self.tzinfo.utcoffset(self)
-
dst() − If tzinfo is None, returns None, else returns self.tzinfo.dst(self)
-
tzname() − If tzinfo is None, returns None, else returns self.tzinfo.tzname(self)
-
timetuple() − Return a time.struct_time such as returned by time.localtime().
-
atetime.toordinal() − Return the proleptic Gregorian ordinal of the date.
-
timestamp() − Return POSIX timestamp corresponding to the datetime instance.
-
isoweekday() − Return day of the week as an integer, where Monday is 1, Sunday is 7.
-
isocalendar() − Return a named tuple with three components: year, week and weekday.
-
isoformat(sep='T', timespec='auto') − Return a string representing the date and time in ISO 8601 format
-
str() − For a datetime instance d, str(d) is equivalent to d.isoformat(' ').
-
ctime() − Return a string representing the date and time:
-
strftime(format) − Return a string representing the date and time, controlled by an explicit format string.
-
format(format) − Same as strftime().
Example
from datetime import datetime, date, time, timezone
# Using datetime.combine()
d = date(2022, 4, 20)
t = time(12, 30)
datetime.combine(d, t)
# Using datetime.now()
d = datetime.now()
print (d)
# Using datetime.strptime()
dt = datetime.strptime("23/04/20 16:30", "%d/%m/%y %H:%M")
# Using datetime.timetuple() to get tuple of all attributes
tt = dt.timetuple()
for it in tt:
print(it)
# Date in ISO format
ic = dt.isocalendar()
for it in ic:
print(it)
它将生成以下 output −
It will produce the following output −
2023-04-20 15:12:49.816343
2020
4
23
16
30
0
3
114
-1
2020
17
4
Python timedelta Object
timedelta 对象表示两个日期或两个时间对象之间的持续时间。
The timedelta object represents the duration between two dates or two time objects.
Syntax
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
在内部,属性存储在日、秒和微秒中。其他参数被转换为这些单位 −
Internally, the attributes are stored in days, seconds and microseconds. Other arguments are converted to those units −
-
A millisecond is converted to 1000 microseconds.
-
A minute is converted to 60 seconds.
-
An hour is converted to 3600 seconds.
-
A week is converted to 7 days.
然后将天、秒和微秒标准化,以便表示唯一。
While days, seconds and microseconds are then normalized so that the representation is unique.
Example
以下示例显示了 Python 在内部仅存储日、秒和微秒。
The following example shows that Python internally stores days, seconds and microseconds only.
from datetime import timedelta
delta = timedelta(
days=100,
seconds=27,
microseconds=10,
milliseconds=29000,
minutes=5,
hours=12,
weeks=2
)
# Only days, seconds, and microseconds remain
print (delta)
它将生成以下 output −
It will produce the following output −
114 days, 12:05:56.000010
Example
以下例子展示了如何将 timedelta 对象添加到日期时间对象。
The following example shows how to add timedelta object to a datetime object.
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)
它将生成以下 output −
It will produce the following output −
Date after 4 days: 2023-04-24 18:05:39.509905
Date before 15 days: 2023-04-05 18:05:39.509905
Class Attributes of timedelta Object
-
timedelta.min − The most negative timedelta object, timedelta(-999999999).
-
timedelta.max − The most positive timedelta object, timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999).
-
timedelta.resolution − The smallest possible difference between non-equal timedelta objects, timedelta(microseconds=1)
Example
from datetime import timedelta
# Getting minimum value
min = timedelta.min
print("Minimum value:", min)
max = timedelta.max
print("Maximum value", max)
它将生成以下 output −
It will produce the following output −
Minimum value: -999999999 days, 0:00:00
Maximum value 999999999 days, 23:59:59.999999
Instance Attributes of timedelta Object
由于 timedelta 对象在内部只存储日、秒和微秒,因此它们是 timedelta 对象的唯一实例属性。
Since only day, second and microseconds are stored internally, those are the only instance attributes for a timedelta object.
-
days − Between -999999999 and 999999999 inclusive
-
seconds − Between 0 and 86399 inclusive
-
microseconds − Between 0 and 999999 inclusive