赞
踩
Python 中提供了 Python DateTime 模块,用于处理日期和时间。在 python 中,DateTime 是一个内置模块,而不是一个原始数据类型,我们只需要导入上面提到的模块即可将日期作为日期对象使用。
有没有想过银行系统如何管理日期和时间,比如他们如何计算贷款的剩余期限。那么,答案就在于python的python datetime模块的功能。继续阅读以了解更多信息。
Python 中提供了 DateTime 模块,用于处理日期和时间。在python DateTime中,是一个内置模块,而不是一个原始数据类型,我们只需要导入上面提到的模块就可以将日期作为日期对象使用。
在python的datetime python模块中有几个类,可以帮助处理日期和时间。此外,这些类有很多函数,我们可以从中提取日期和时间。
首先,您需要使用以下代码导入 python 的 python datetime 模块,以便您可以使用其内置类来获取当前日期和时间等。
import datetime
'运行
语法
- import datetime
-
- var1 = datetime.date(YYYY, MM, DD)
-
- # This will convert the numeral date to the date object
'运行
例
- import datetime
-
- userdate = datetime.date(2021, 10, 20)
-
- print('userdate: ', userdate)
- print('type of userdate: ', type(userdate))
'运行
输出:
- success
- userdate: 2021-10-20
- type of userdate: <class 'datetime.date'>
代码说明
- 然后,我们将日期时间对象保存到变量中。
- 然后我们打印变量以及输出如下的变量类型。
- 此类有助于将数字日期和时间属性转换为 YYYY-MM-DD hr:min:s:ms 形式的日期时间格式。
此类接受 7 个属性 Year、Month、Day、Hour、Minutes、Seconds、MilliSeconds,顺序如下(年、月、日、小时、分钟、秒、毫秒)。
语法
- import datetime
-
- var1 = datetime.datetime(YYYY, MM, DD, hr, min, s, ms)
-
- # This will convert the numeral date to the datetime object in the form of
- YYYY-MM-DD hr:min:s:ms.
'运行
例
- import datetime
-
- userdatetime = datetime.datetime(2019, 5, 10, 17, 30, 20, 154236)
-
- print('userdatetime: ', userdatetime)
- print('type of userdatetime: ', type(userdatetime))
输出:
- success
- userdatetime: 2019-05-10 14:30:20.154236
- type of userdatetime: <class 'datetime.datetime'>
'运行
代码说明
现在,我们可以使用 datetime 模块的 date 类。
此类有助于将数字日期属性转换为 YYYY-MM-DD 形式的日期格式。
此类接受 3 个属性:年、月和日,顺序如下(年、月、日)。
语法
- import datetime
-
- var1 = datetime.date(YYYY, MM, DD)
-
- # This will convert the numeral date to the date object
例
- import datetime
-
- userdate = datetime.date(2021, 9, 15)
-
- print('userdate: ', userdate)
- print('type of userdate: ', type(userdate))
'运行
输出
- userdate: 2021-09-15
- type of userdate: <class 'datetime.date'>
代码说明
正如我们所看到的,我们已经将数字数据更改为 datetime 对象,并且可以通过下面打印的对象类型来验证这一点。
现在,我们可以使用 python datetime 模块的 time 类。
Time 类返回用户所在区域的本地时间。
时间类接受 5 个属性:小时、分钟、秒、微秒和折叠,顺序如下(时、分、秒、微秒、折叠)。
上面提到的所有属性都是可选的,但所有属性的初始值都是 0。
语法
- import datetime
-
- # returns the time with all it's value as 0 like 00:00:00
- var1 = datetime.time()
-
- # returns the time with the value which are specified by the user in the attributes
- var2 = datetime.time(hour=?, minute=?, second=?, microsecond=?)
'运行
例
- import datetime
-
- time1 = datetime.time()
- print('without passing any attribute: ', time1)
-
- time2 = datetime.time(hour=12, minute=55, second=50)
- print('by passing hour, minute and second attributes: ', time2)
-
- time1 = time1.replace(hour=17)
- print('by replacing the hour attribute in time1: ', time1)
-
- time2 = time2.replace(minute=00)
- print('by replacing the minute attribute in time2: ', time2)
输出
- without passing any attribute: 00:00:00
- by passing hour, minute and second attributes: 12:55:50
- by replacing the hour attribute in time1: 17:00:00
- by replacing the minute attribute in time2: 12:00:50
'运行
代码说明
现在,我们可以使用 datetime 模块的 datetime python 类。 此类有助于将数字日期和时间属性转换为 YYYY-MM-DD hr:min:s:ms 形式的日期时间格式。
此类接受 7 个属性 Year、Month、Day、Hour、Minutes、Seconds、MilliSeconds,顺序如下(年、月、日、小时、分钟、秒、毫秒)。
语法
- import datetime
-
- var1 = datetime.datetime(YYYY, MM, DD, hr, min, s, ms)
-
- # This will convert the numeral date to the datetime object in the form of
- YYYY-MM-DD hr:min:s:ms.
例
- import datetime
-
- userdatetime = datetime.datetime(2021, 9, 15, 20, 55, 20, 562789)
-
- print('userdatetime: ', userdatetime)
- print('type of userdatetime: ', type(userdatetime))
'运行
输出
- userdatetime: 2021-09-15 20:55:20.562789
- type of userdatetime: <class 'datetime.datetime'>
代码说明
正如我们所看到的,我们已将数字 python datatime 更改为 datetime 对象,并且可以通过下面打印的对象类型进行验证。
现在,我们可以使用 datetime 模块的 timedelta 类。
此类有助于查找 datetime.timedelta 类提供的 2 个日期/时间之间的差异。无论日期/时间的差异是正数还是负数。
此类接受多个参数,如周、天、小时、分钟、秒、毫秒和微秒。而且,这些参数的默认值为零。
语法
- import datetime
-
- var1 = datetime.timedelta(weeks=?, days=?, hours=?, minutes=?, seconds=?,
- milliseconds=?, microsecond=?)
-
- # This will return the exact date & time object by using all the attributes
- used by the user.
'运行
例
- import datetime
-
- data1= datetime.timedelta(days=1, hours=23, minutes=30)
- print('data1: ', data1)
-
- data2= datetime.timedelta(days=4, hours=11, minutes=30)
- print('data2: ', data2)
-
- difference = data2-data1
- print('difference between data2 and data1: ', difference)
输出
- data1: 1 day, 23:30:00
- data2: 4 days, 11:30:00
- difference between data2 and data1: 2 days, 12:00:00
'运行
代码说明
正如我们所看到的,我们已经打印了下面 2 个日期的差异。
我们用来获取当前系统时间的函数 .now() 没有任何关于时区的信息。在大多数情况下,需要时区信息。因此,在这种情况下,使用 tzinfo 抽象类。由于它是一个抽象类,所以它不能直接实例化。
datetime 对象的构造函数接受 Tzinfo 类的实例。
时区代表标准时间,这取决于考虑世界的哪个部分。
datetime.now() 返回用户所在的部分的本地时间。当地时间与该特定地区的时区无关。
我们可以再导入一个内置模块 pytz,以使用世界不同地区的时区。使用下面提到的代码导入模块:
import pytz
语法
- import datetime
-
- #added another module for using different time zones.
- import pytz
-
- #return the local time of that area
- var1 = datetime.now()
-
- # return the standard utc time
- var2 = datetime.now(pytz.utc)
-
- # return the us/central timezone
- var3 = datetime.now(pytz.timezone('US/CENTRAL'))
-
'运行
例
- import datetime
- import pytz
-
-
- localtime= datetime.datetime.now()
- print('local time: ', localtime)
-
- utctime = datetime.datetime.now(pytz.utc)
- print('UTC time zone: ', utctime)
-
- ustime = datetime.datetime.now(pytz.timezone('US/CENTRAL'))
- print('US time zone: ', ustime)
'运行
输出
- local time: 2021-10-15 01:37:39.603581
- UTC time zone: 2021-10-14 20:07:39.603716+00:00
- US time zone: 2021-10-14 15:07:39.626474-05:00
'运行
示例说明
此类有助于将数字日期属性转换为 YYYY-MM-DD 形式的日期格式。
此类接受 3 个属性:年、月和日,顺序如下(年、月、日)。
语法
- import datetime
-
- var1 = datetime.date(YYYY, MM, DD)
-
- # This will convert the numeral date to the date object
例
- import datetime
-
- dateByUser = datetime.date(2018, 12, 31)
- print('dateByUser: ', dateByUser)
- print('type of dateByUser: ', type(dateByUser))
-
'运行
输出
- dateByUser: 2018-12-31
- type of dateByUser: <class 'datetime.date'>
示例说明
正如我们所看到的,我们已将数字 datatime 更改为 datetime 对象,并且可以通过下面打印的对象类型来验证这一点。
Date 类的此函数以“YYYY-MM-DD”的格式返回输出屏幕上的今天日期。
例
- import datetime
-
- print("today's date: ", datetime.date.today())
'运行
输出
- today's date: 2021-10-16
min 函数返回最早的可表示日期。这使用 3 个属性“MinYear”、“Month”和“Day”,顺序如下(datetime。MINYEAR、月、日)。
例
- import datetime
-
- print('earliest year which can be represented: ',
- datetime.date(datetime.MINYEAR, 12, 1))
'运行
输出
earliest year which can be represented: 0001-12-01
.max 函数返回最新的可表示日期。这使用 3 个属性“MaxYear”、“Month”和“Day”,顺序如下(datetime。MAXYEAR、月、日)。
例
- import datetime
-
- print('latest year which can be represented: ',
- datetime.date(datetime.MAXYEAR, 2, 25))
'运行
输出
latest year which can be represented: 9999-02-25
此函数返回用户输入的日期的天数。它给出了从 1 到 30/31(或指定月份中的精确天数)的计数,两者都包括在内。
例
- import datetime
-
- dateByUser = datetime.date(2020, 5, 27)
- print('day count of the date entered by the user: ', dateByUser.day)
'运行
输出
day count of the date entered by the user: 27
此函数返回用户输入的日期的月计数。它给出了从 1 到 12 的计数,两者都包括 1 和 12。
例
- import datetime
-
- dateByUser = datetime.date(2024, 2, 29)
- print('month count of the date entered by the user:', dateByUser.month)
'运行
输出
month count of the date entered by the user: 2
此函数返回用户输入的日期的年份计数。它给出了从 MINYEAR 到 MAXYEAR 的计数,两者都包括在内。
例
- import datetime
-
- dateByUser = datetime.date(2030, 10, 15)
- print('year of the date entered by the user:', dateByUser.year)
'运行
输出
year of the date entered by the user: 2030
此功能帮助我们以不同类型的格式表示日期,例如短/长日(周一、星期一)、短/长年(21、2021)、数字/字母月份(03、三月)。
下图表示用于表示不同类型格式的日期的符号。
例
- import datetime
-
- todaydatetime = datetime.datetime.now()
-
- print('current date and time: ', todaydatetime)
- print('fetched out year from current date: ', todaydatetime.strftime('%Y'))
- print('fetched out month from current date: ', todaydatetime.strftime('%B'))
- print('fetched out day from current date: ', todaydatetime.strftime('%A'))
- print('formatted the time from above generated date time: ', todaydatetime.strftime('%H:%M:%S'))
- print(todaydatetime.strftime('formatted both date and time: ', "%d/%m/%Y, %H:%M:%S"))
'运行
输出
- current date and time: 2021-10-17 12:14:52.394962
- fetched out year from current date: 2021
- fetched out month from current date: October
- fetched out day from current date: Sunday
- formatted the time from above generated date time: 12:14:52
- formatted both date and time: 17/10/2021, 12:14:52
'运行
示例说明
我们有两种方法可以找出当前日期,如下所述:
.today() 用于返回当前本地日期。我们可以从 datetime 模块的 date 类中使用它来获取当前日期。
法典
- import datetime
-
- currentdate = datetime.date.today()
- print('current date: ', currentdate)
'运行
输出
current date: 2021-10-17
'运行
.now() 用于将当前本地日期和时间作为 datetime 对象返回。因此,我们可以做的是,我们可以格式化 datetime 对象以仅获取当前日期。
法典
- import datetime
-
- currentdate = datetime.datetime.now()
-
- print('raw current date and time generated', currentdate)
- print('current date formatted from date and time',
- currentdate.strftime("%d/%m/%Y"))
'运行
输出
- raw current date and time generated 2021-10-17 12:40:15.974292
- current date formatted from date and time 17/10/2021
python datetime 模块的 datetime python 类有一个函数 strptime(),用于将时间戳字符串转换为 datetime python 对象。
.strptime() 接受 2 个属性 timestamp 和格式,我们可以将其转换为 datetime 对象。
语法
- import datetime
-
- var1 = datetime.strptime('TimeStamp', 'Format in which we want to print the datetime object')
-
- TimeStamps are represented as: 2021-01-02T10::52::69.125777
- and
- Formats are represented as: %Y-%B-%AT%H::%M::%S.%f
'运行
例
- import datetime
-
- datetimeObj = datetime.datetime.strptime('2002-01-02T10::52::59.456777'
- ,'%Y-%m-%dT%H::%M::%S.%f')
-
- print('changed timestamp string to datetime object', datetimeObj)
- print('verifying the type of changed format: ', type(datetimeObj))
输出
- changed timestamp string to datetime object 2002-01-02 10:52:59.456777
- verifying the type of changed format: <class 'datetime.datetime'>
'运行
示例说明
时间戳是用于查找特定事件发生时间的字符序列,通常给出一天中的日期和时间,精确到几分之一秒。
让我们看看如何使用 datetime python 模块获取当前时间戳。
语法
- import datetime
-
- # Date entered by the user/ Current date
- var1 = datetime.now()
-
- var1ToTimestamp = var1.timestamp()
*例
- import datetime
-
- timestamp = datetime.datetime.now()
-
- print('current date and time', timestamp)
- print('current timestamp', timestamp.timestamp())
'运行
输出
- current date and time 2021-10-17 13:43:04.221229
- current timestamp 1634458384.221229
代码解释
法典
- import datetime
-
- timestamp = datetime.datetime.now()
-
- print('full name of the day of the date used: ', timestamp.strftime('%A'))
'运行
输出
full name of the day of the date used: Sunday
代码解释
法典
- import datetime
-
- timestamp = datetime.datetime.now()
-
- print('day count of the day of the date used: ', timestamp.strftime('%d'))
'运行
输出
day count of the day of the date used: 17
代码解释
主要功能
UserDefined 函数
下面提到的图像可帮助您更好地可视化我们如何打印两个日期之间的所有日期列表。
法典
- import datetime
-
- def datediff(date1, date2):
- for n in range(int ((date2 - date1).days)+1):
- yield date1 + datetime.timedelta(n)
-
- startdate = datetime.date(2021, 10, 1)
- enddate = datetime.date(2021, 10, 11)
- print('List of dates between ', startdate.strftime("%d-%m-%y"),
- ' and ', enddate.strftime("%d-%m-%y"), ' is/are: ')
- for date in datediff(startdate, enddate):
- print(date.strftime("%d-%m-%Y"))
'运行
输出
- List of dates between 01-10-21 and 11-10-21 is/are:
- 01-10-2021
- 02-10-2021
- 03-10-2021
- 04-10-2021
- 05-10-2021
- 06-10-2021
- 07-10-2021
- 08-10-2021
- 09-10-2021
- 10-10-2021
- 11-10-2021
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。