Time management black technology: datetime function in Python helps you get twice the result with half the effort


 

introduce

In Python, the datetime module is the standard library for working with dates and times. It provides a collection of powerful functions and classes for working with dates, times, time intervals, and more. This article will discuss in depth how to use the datetime module, from entry to mastery.


Table of contents

  1. import the datetime module

  2. Get the current date and time

  3. Create custom dates and times

  4. format date and time

  5. Calculation of time intervals

  6. Date addition and subtraction

  7. Compare dates and times

  8. Handling time zones

  9. Time to sleep and wait

  10. Summarize


1. Import datetime module

First, we need to import the datetime module in order to use the functions and classes it provides.

# 导入datetime模块
import datetime

In the above code, we import the datetime module using the import keyword.

2. Get the current date and time

The datetime module provides the datetime class, which can be used to represent dates and times. Through the now() method of the datetime class, we can get the current date and time.

# 导入datetime模块
import datetime

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

print("当前日期和时间:", now)

In the above code, we use the now() method of the datetime class of the datetime module to get the current date and time, and save the result in the variable now.

3. Create a custom date and time

In addition to getting the current date and time, we can also create a custom date and time. Using the constructor of the datetime class, you can specify parameters such as year, month, day, hour, minute, and second to create a custom date and time.

# 导入datetime模块
import datetime

# 创建自定义的日期和时间
custom_date = datetime.datetime(2023, 7, 30, 12, 30, 45)

print("自定义的日期和时间:", custom_date)

In the above code, we use the constructor of the datetime class of the datetime module, pass in parameters such as year, month, day, hour, minute, second, etc., create a custom date and time, and save the result in the variable custom_date .

4. Format date and time

The datetime object can format the date and time according to the specified format by calling the strftime() method.

# 导入datetime模块
import datetime

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

# 格式化日期和时间输出
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")

print("格式化后的日期和时间:", formatted_date)

In the above code, we use the strftime() method to format the current date and time as a string of "YYYY-MM-DD HH:MM:SS" and store the result in the variable formatted_date.

5. Calculation of time intervals

The datetime module provides the timedelta class, which can be used to represent time intervals. We can use the constructor of the timedelta class to pass in parameters such as days, hours, minutes, seconds, etc. to create a time interval.

# 导入datetime模块
import datetime

# 创建时间间隔
time_delta = datetime.timedelta(days=5, hours=3, minutes=30)

print("时间间隔:", time_delta)

In the above code, we use the constructor of the timedelta class of the datetime module, pass in parameters such as days=5, hours=3, minutes=30, create a time interval, and save the result in the variable time_delta.

6. Date addition and subtraction

By using the timedelta class, we can add and subtract dates to get new dates.

# 导入datetime模块
import datetime

# 获取当前日期
current_date = datetime.datetime.now()

# 创建时间间隔
time_delta = datetime.timedelta(days=10)

# 进行日期的加减运算
new_date = current_date + time_delta

print("加上时间间隔后的日期:", new_date)

In the above code, we get the current date and create an interval time_delta of 10 days. Then, by adding the current date and the time interval, a new date new_date is obtained.

7. Comparing dates and times

We can use comparison operators to compare the size of two dates and times.

# 导入datetime模块
import datetime

# 创建两个日期
date1 = datetime.datetime(2023, 7, 30)
date2 = datetime.datetime(2024, 7, 30)

# 比较日期
if date1 < date2:
    print("date1在date2之前")
elif date1 > date2:
    print("date1在date2之后")
else:
    print("date1和date2相同")

In the above code, we create two dates date1 and date2, and use comparison operators to compare them to determine their size relationship.

8. Handling time zones

When dealing with dates and times, we sometimes need to consider time zones. The timezone class is provided in the datetime module to represent time zones.

# 导入datetime模块
import datetime

# 导入timezone类
from datetime import timezone

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

# 创建带有时区信息的日期和时间
date_with_timezone = current_date.replace(tzinfo=timezone.utc)

print("带有时区信息的日期和时间:", date_with_timezone)

In the above code, we use the replace() method to add the time zone information to the current date and time to get a date and time date_with_timezone with time zone information.

9. Time to sleep and wait

The sleep() function in the datetime module can be used to pause a program for a period of time.

# 导入datetime模块
import datetime
import time

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

print("当前日期和时间:", current_date)

# 暂停5秒钟
time.sleep(5)

# 再次获取当前日期和时间
current_date = datetime.datetime.now()

print("5秒后的日期和时间:", current_date)

In the above code, we first get the current date and time, then use the time.sleep(5) function to pause the program for 5 seconds, and finally get the current date and time again to verify the pause effect.

10. Summary

Through the explanation in this article, we understand the basic usage of the datetime module, from obtaining the current date and time, creating a custom date and time, to formatting date and time output, calculating time intervals, adding and subtracting dates, and comparing dates and time, handling timezones and pausing for waiting. The datetime module is a powerful tool for dealing with dates and times. Proficiency in its use will help us deal with date and time-related operations more flexibly and efficiently in Python development.

Guess you like

Origin blog.csdn.net/Rocky006/article/details/132225012