搜尋
首頁後端開發Python教學使用Python日期庫pendulum來處理日期和時間

使用Python日期庫pendulum來處理日期和時間

Apr 23, 2023 pm 02:43 PM
python日期庫pendulum

一个好用的 Python 日期库 -- pendulum

關於日期處理,Python 提供了很多的函式庫,像是標準函式庫 datetime、第三方函式庫 dateutil、arrow 等等。

在使用前需要先安裝,直接 pip install pendulum 即可。

下面來看用法,首先是 datetime, date, time 的建立。

import pendulum
dt = pendulum.datetime(
 2022, 3, 28, 20, 10, 30)
print(dt.__class__)
print(dt)
"""
<class 'pendulum.datetime.DateTime'>
2022-03-28T20:10:30+00:00
"""
# 创建的对象是 DateTime 类型
# 并且带有时区,默认是 UTC
# 我们可以换一个时区
dt = pendulum.datetime(
 2022, 3, 28, 20, 10, 30, tz="Asia/Shanghai")
print(dt)
"""
2022-03-28T20:10:30+08:00
"""
# 如果不想要时区,那么指定 tz=None
dt = pendulum.datetime(
 2022, 3, 28, 20, 10, 30, tz=None)
print(dt)
"""
2022-03-28T20:10:30
"""
# 然后是 date 的创建
d = pendulum.date(2022, 3, 28)
print(d.__class__)
print(d)
"""
<class 'pendulum.date.Date'>
2022-03-28
"""
# time 的创建
t = pendulum.time(20, 10, 30)
print(t.__class__)
print(t)
"""
<class 'pendulum.time.Time'>
20:10:30
"""

如果建立 datetime 時,時區預設是 UTC。如果不想要時區,或希望時區是本地時區,那麼 pendulum 還特別提供了兩個方法。

import pendulum
# 创建 datetime 时设置为本地时区
# 还是调用了 pendulum.datetime 函数
# 但是 tz 被设置成了 pendulum.local_timezone()
dt = pendulum.local(
 2022, 3, 28, 20, 10, 30)
print(dt)
"""
2022-03-28T20:10:30+08:00
"""
print(pendulum.local_timezone())
"""
Timezone('Asia/Shanghai')
"""
# 创建 datetime 时不设置时区
# 内部也是调用了 pendulum.datetime 函数
# 但是 tz 为 None
dt = pendulum.naive(2022, 3, 28, 20, 10, 30)
print(dt)
"""
2022-03-28T20:10:30
"""

然後 pendulum 還提供了幾個方法,例如創建當前的 datetime,date 等等。

import pendulum
# 创建当前的 datetime
# 默认是本地时区,但时区可以指定
dt = pendulum.now()
print(dt)
"""
2022-05-29T20:40:49.632182+08:00
"""
# 创建当前的 date,但返回的仍是 datetime
# 只不过时分秒均为 0,同样可以指定时区
dt = pendulum.today()
print(dt)
"""
2022-05-29T00:00:00+08:00
"""
# 获取明天对应的 date
# 返回的是 datetime,时分秒为 0
# 时区可以指定,默认是本地时区
dt = pendulum.tomorrow()
print(dt)
"""
2022-05-30T00:00:00+08:00
"""
# 获取昨天对应的 date
dt = pendulum.yesterday()
print(dt)
"""
2022-05-28T00:00:00+08:00
"""

我們也可以根據時間戳記或字串來建立:

import pendulum
# 根据时间戳创建
dt1 = pendulum.from_timestamp(1653828466)
dt2 = pendulum.from_timestamp(1653828466,
 tz=pendulum.local_timezone())
print(dt1)
print(dt2)
"""
2022-05-29T12:47:46+00:00
2022-05-29T20:47:46+08:00
"""
# 根据字符串创建
dt1 = pendulum.parse("2020-05-03 12:11:33")
dt2 = pendulum.parse("2020-05-03 12:11:33",
tz=pendulum.local_timezone())
print(dt1)
print(dt2)
"""
2020-05-03T12:11:33+00:00
2020-05-03T12:11:33+08:00
"""

datetime、date、time 的創建我們說完了,然後再來看看它們支援的操作,這也是最核心的部分。

datetime 相關操作

操作非常多,我們逐一介紹。

import pendulum
dt = pendulum.local(
 2022, 3, 28, 20, 10, 30)
# 获取 date 部分和 time 部分
print(dt.date())
print(dt.time())
"""
2022-03-28
20:10:30
"""
# 替换掉 dt 的某部分,返回新的 datetime
# 年月日时分秒、以及时区都可以替换
print(dt.replace(year=9999))
"""
9999-03-28T20:10:30+08:00
"""
# 转成时间戳
print(dt.timestamp())
"""
1648469430.0
"""
# 返回年、月、日、时、分、秒、时区
print(dt.year, dt.month, dt.day)
print(dt.hour, dt.minute, dt.second)
print(dt.tz)
"""
2022 3 28
20 10 30
Timezone('Asia/Shanghai')
"""

然後是產生字串,pendulum.DateTime 物件可以轉換成各種格式的日期字串。

import pendulum
dt = pendulum.local(
 2022, 3, 28, 20, 10, 30)
# 下面四个最为常用
print("datetime:", dt.to_datetime_string())
print("date:", dt.to_date_string())
print("time:", dt.to_time_string())
print("iso8601:", dt.to_iso8601_string())
"""
datetime: 2022-03-28 20:10:30
date: 2022-03-28
time: 20:10:30
iso8601: 2022-03-28T20:10:30+08:00
"""
# 当然还支持很多其它格式,不过用的不多
# 随便挑几个吧
print("atom:", dt.to_atom_string())
print("rss:", dt.to_rss_string())
print("w3c:", dt.to_w3c_string())
print("cookie:", dt.to_cookie_string())
print("rfc822:", dt.to_rfc822_string())
"""
atom: 2022-03-28T20:10:30+08:00
rss: Mon, 28 Mar 2022 20:10:30 +0800
w3c: 2022-03-28T20:10:30+08:00
rfc822: Mon, 28 Mar 22 20:10:30 +0800
"""

我們有時也需要判斷目前日期是星期幾、在目前這一年是第幾天等等,pendulum 也已經幫我們封裝好了。

import pendulum
dt = pendulum.local(
 2022, 3, 28, 20, 10, 30)
# 返回星期几
# 注意:星期一到星期天分别对应 1 到 7
print(dt.isoweekday())# 1
# 返回一年当中的第几天
# 范围是 1 到 366
print(dt.day_of_year)# 87
# 返回一个月当中的第几天
print(dt.days_in_month)# 31
# 返回一个月当中的第几周
print(dt.week_of_month)# 5
# 返回一年当中的第几周
print(dt.week_of_year)# 13
# 是否是闰年
print(dt.is_leap_year())# False

最後就是日期的運算,這是 pendulum 最強大的地方,至於為什麼強大,我們示範一下就知道了。

import pendulum
dt = pendulum.local(
 2022, 3, 30, 20, 10, 30)
# 返回下一个月的今天
print(dt.add(months=1))
"""
2022-04-30T20:10:30+08:00
"""
# 返回上一个月的今天
# 但是上一个月是 2 月,并且是平年
# 所以最多 28 天
print(dt.add(months=-1))
"""
2022-02-28T20:10:30+08:00
"""
# 我们看到处理的非常完美
# 该方法的原型如下,年月日时分秒都是支持的,当然还有星期也支持
"""
def add(
 self,
 years=0,
 months=0,
 weeks=0,
 days=0,
 hours=0,
 minutes=0,
 seconds=0,
 microseconds=0,
):
"""

像 Python 的內建模組 datetime 在將日期相加的時候,最多支援到天,我們無法計算下一周、下個月、下一年的日期。而 pendulum 則可以很方便地處理,這也是我最喜歡的一點。

當然啦,add 裡面的值是正,相當於日期往後退;值為負,相當於日期往前推。

然後是兩個日期還可以做減法:

import pendulum
dt1 = pendulum.local(
 2021, 1, 20, 11, 22, 33)
dt2 = pendulum.local(
 2022, 3, 30, 20, 10, 30)
period = dt2 - dt1
# 返回的是 Period 对象
# 相当于 datetime 模块里面的 timedelta
print(period.__class__)
"""
<class 'pendulum.period.Period'>
"""
# 但是功能方面,Period 要强大很多
# 两者差了多少年
print(period.in_years())# 1
# 两者差了多少个月
print(period.in_months())# 14
# 两者差了多少个星期
print(period.in_weeks())# 62
# 两者差了多少天
print(period.in_days())# 434
# 两者差了多少个小时
print(period.in_hours())# 10424
# 两者差了多少分钟
print(period.in_minutes())# 625487
# 两者差了多少秒
print(period.in_seconds())# 37529277

功能非常強大,Python 的datetime 模組裡面的timedelta 最多只能計算兩個日期差了多少天,而這裡年月日時分秒均可。

以上就是本文的內容,當然 pendulum 的功能其實不只我們上面說的那些,有興趣的話可以參考官網,但常用的差不多就這些東西。

以上是使用Python日期庫pendulum來處理日期和時間的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:51CTO.COM。如有侵權,請聯絡admin@php.cn刪除
列表和陣列之間的選擇如何影響涉及大型數據集的Python應用程序的整體性能?列表和陣列之間的選擇如何影響涉及大型數據集的Python應用程序的整體性能?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

說明如何將內存分配給Python中的列表與數組。說明如何將內存分配給Python中的列表與數組。May 03, 2025 am 12:10 AM

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

您如何在Python數組中指定元素的數據類型?您如何在Python數組中指定元素的數據類型?May 03, 2025 am 12:06 AM

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

什麼是Numpy,為什麼對於Python中的數值計算很重要?什麼是Numpy,為什麼對於Python中的數值計算很重要?May 03, 2025 am 12:03 AM

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

討論'連續內存分配”的概念及其對數組的重要性。討論'連續內存分配”的概念及其對數組的重要性。May 03, 2025 am 12:01 AM

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

您如何切成python列表?您如何切成python列表?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

在Numpy陣列上可以執行哪些常見操作?在Numpy陣列上可以執行哪些常見操作?May 02, 2025 am 12:09 AM

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,減法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Python的數據分析中如何使用陣列?Python的數據分析中如何使用陣列?May 02, 2025 am 12:09 AM

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器