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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

See all articles