Pendulum Detailed Explanation 1 - Pendulum Library Getting Started Guide - The Art of Time

write at the beginning

Time is an indispensable element in the programming world. Whether it is event scheduling, data analysis, or user interface display, time plays a key role. However, in Python's standard library datetime, we often face cumbersome operations and limitations. In order to get rid of these constraints, we introduced a more powerful and flexible time processing library - Pendulum.

1 Introduction to Pendulum

Pendulum is an elegant and powerful time processing library designed specifically for Python. In comparison datetime, Pendulum provides more functions and a simpler interface, making time processing easy and enjoyable. Let’s take a look at its basic features and why it is the artist of time.

2 Installation and basic setup:

To start our journey through time, we first need to install the Pendulum library. Use the following command:

pip install pendulum

After the installation is complete, we can start using Pendulum in our projects. Import the Pendulum module and set the default time zone:

import pendulum

# 设置默认时区为上海
pendulum.set_locale("zh")
pendulum.set_timezone("Asia/Shanghai")

3 Basic usage

Pendulum makes the creation and manipulation of time objects very simple. For example, to get the current time, we only need:

now = pendulum.now()
print(now)

This simple operation returns a Pendulum object containing the current date and time. Even more interesting is that we can easily add and subtract time:

future_date = now.add(days=7)
print(future_date)

When using Pendulum to add and subtract dates, you can add different time intervals as needed, including years, months, days, hours, minutes, seconds, etc. Pendulum provides a clear API, making date operations simple and flexible.

3.1. Basic addition and subtraction of year, month and day

import pendulum

# 获取当前日期和时间
now = pendulum.now()

# 加一年
one_year_later = now.add(years=1)
print("一年后:", one_year_later)

# 减两个月
two_months_ago = now.subtract(months=2)
print("两个月前:", two_months_ago)

# 加十天
ten_days_later = now.add(days=10)
print("十天后:", ten_days_later)

3.2. Separate addition and subtraction of hours, minutes and seconds

import pendulum

# 获取当前日期和时间
now = pendulum.now()

# 加三小时
three_hours_later = now.add(hours=3)
print("三小时后:", three_hours_later)

# 减四分钟
four_minutes_ago = now.subtract(minutes=4)
print("四分钟前:", four_minutes_ago)

# 加五秒钟
five_seconds_later = now.add(seconds=5)
print(<

Guess you like

Origin blog.csdn.net/qq_41780234/article/details/135375803