Table of Contents
Datetime related operations
Home Backend Development Python Tutorial Use the Python date library pendulum to handle dates and times

Use the Python date library pendulum to handle dates and times

Apr 23, 2023 pm 02:43 PM
python Date library pendulum

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

Regarding date processing, Python provides many libraries, such as the standard library datetime, third-party libraries dateutil, arrow, etc.

You need to install it before using it, just pip install pendulum.

Let’s take a look at the usage. The first is the creation of datetime, date, and 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
"""
Copy after login

If you create a datetime, the time zone defaults to UTC. If you don't want the time zone, or you want the time zone to be the local time zone, pendulum also provides two methods.

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
"""
Copy after login

Then pendulum also provides several methods, such as creating the current datetime, date, etc.

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
"""
Copy after login

We can also create based on timestamp or string:

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
"""
Copy after login

We have finished talking about the creation of datetime, date, and time, and then let’s take a look at the operations they support, which is also the core part.

There are many operations, we will introduce them one by one.

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')
"""
Copy after login

Then the string is generated. The pendulum.DateTime object can be converted into date strings in various formats.

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
"""
Copy after login

Sometimes we also need to determine what day of the week the current date is, what day it is in the current year, etc. Pendulum has also packaged it for us.

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
Copy after login

The last thing is the date operation, which is the most powerful part of pendulum. As for why it is powerful, we will know after we demonstrate it.

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,
):
"""
Copy after login

Like Python's built-in module datetime, when adding dates, it supports up to days. We cannot calculate the dates of the next week, next month, and next year. Pendulum, on the other hand, is easy to handle, which is what I love most about it.

Of course, if the value in add is positive, it is equivalent to moving the date backward; if the value is negative, it is equivalent to pushing the date forward.

Then you can also subtract two dates:

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
Copy after login

The function is very powerful. The timedelta in Python's datetime module can only calculate the number of days difference between the two dates at most, and here the year and month Day, hour, minute and second are available.

The above is the content of this article. Of course, the functions of pendulum are actually more than what we mentioned above. If you are interested, you can refer to the official website, but these are the most commonly used ones.

The above is the detailed content of Use the Python date library pendulum to handle dates and times. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to efficiently integrate Node.js or Python services under LAMP architecture? How to efficiently integrate Node.js or Python services under LAMP architecture? Apr 01, 2025 pm 02:48 PM

Many website developers face the problem of integrating Node.js or Python services under the LAMP architecture: the existing LAMP (Linux Apache MySQL PHP) architecture website needs...

What is the reason why pipeline persistent storage files cannot be written when using Scapy crawler? What is the reason why pipeline persistent storage files cannot be written when using Scapy crawler? Apr 01, 2025 pm 04:03 PM

When using Scapy crawler, the reason why pipeline persistent storage files cannot be written? Discussion When learning to use Scapy crawler for data crawler, you often encounter a...

Python Cross-platform Desktop Application Development: Which GUI Library is the best for you? Python Cross-platform Desktop Application Development: Which GUI Library is the best for you? Apr 01, 2025 pm 05:24 PM

Choice of Python Cross-platform desktop application development library Many Python developers want to develop desktop applications that can run on both Windows and Linux systems...

What is the reason why the Python process pool handles concurrent TCP requests and causes the client to get stuck? What is the reason why the Python process pool handles concurrent TCP requests and causes the client to get stuck? Apr 01, 2025 pm 04:09 PM

Python process pool handles concurrent TCP requests that cause client to get stuck. When using Python for network programming, it is crucial to efficiently handle concurrent TCP requests. ...

How to view the original functions encapsulated internally by Python functools.partial object? How to view the original functions encapsulated internally by Python functools.partial object? Apr 01, 2025 pm 04:15 PM

Deeply explore the viewing method of Python functools.partial object in functools.partial using Python...

Python hourglass graph drawing: How to avoid variable undefined errors? Python hourglass graph drawing: How to avoid variable undefined errors? Apr 01, 2025 pm 06:27 PM

Getting started with Python: Hourglass Graphic Drawing and Input Verification This article will solve the variable definition problem encountered by a Python novice in the hourglass Graphic Drawing Program. Code...

How to optimize processing of high-resolution images in Python to find precise white circular areas? How to optimize processing of high-resolution images in Python to find precise white circular areas? Apr 01, 2025 pm 06:12 PM

How to handle high resolution images in Python to find white areas? Processing a high-resolution picture of 9000x7000 pixels, how to accurately find two of the picture...

How to efficiently count and sort large product data sets in Python? How to efficiently count and sort large product data sets in Python? Apr 01, 2025 pm 08:03 PM

Data Conversion and Statistics: Efficient Processing of Large Data Sets This article will introduce in detail how to convert a data list containing product information to another containing...

See all articles