Python automation date and time processing

In Python programming, dealing with dates and times is a very common need. In order to meet these needs, Python provides modules such as time, datetime, and calendar, which provide a rich set of functions and classes that can easily handle operations such as representation, calculation, conversion, and formatting of dates and times. This article will introduce the use of these three modules in detail and deepen understanding through code examples.

1. time module

The time module is a module in the Python standard library for handling time. It provides time-related functions and classes that can be used to represent and manipulate timestamps (times in seconds) and format time operations.

1. Get the timestamp of the current time

The time() function can get the timestamp of the current time, that is, the number of seconds that have passed since 0:00 on January 1, 1970. The sample code is as follows:

import time


timestamp = time.time()
print("当前时间戳:", timestamp)

2. Convert timestamp to struct_time object

The localtime() function converts the timestamp into a struct_time object of the current time zone. If a timestamp is not provided, it returns a struct_time object of the current time. The sample code is as follows:

import time


timestamp = time.time()
local_time = time.localtime(timestamp)
print("当前本地时间:", local_time)

3. Convert struct_time object to timestamp

The mktime() function converts a struct_time object into a timestamp. The sample code is as follows:

import time


local_time = time.localtime()
timestamp = time.mktime(local_time)
print("新的时间戳:", timestamp)

4. Format time

The strftime() function can convert a struct_time object or timestamp into a string in a specified format. The sample code is as follows:

import time


local_time = time.localtime()
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
print("格式化时间:", formatted_time)

5. Parse string into struct_time object

The strptime() function can parse a string into a struct_time object. The sample code is as follows:

import time


parsed_time = time.strptime("2023-09-12 17:20:49", "%Y-%m-%d %H:%M:%S")
print("解析时间:", parsed_time)

2. datetime module

The datetime module is a module in the Python standard library for working with dates and times. It provides date, time, time interval, time difference and other related classes and functions, which can perform operations such as date and time representation, calculation and formatting.

1. Get the current date and time

The datetime.now() function can get the current date and time. The sample code is as follows:

from datetime import datetime


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

2. Get various attributes of date and time

The datetime object contains attributes such as year, month, day, hour, minute, and second, and various parts of the date and time can be obtained through these attributes. The sample code is as follows:

from datetime import datetime


now = datetime.now()
year = now.year
month = now.month
day = now.day
hour = now.hour
minute = now.minute
second = now.second
print("年:", year)
print("月:", month)
print("日:", day)
print("时:", hour)
print("分:", minute)
print("秒:", second)

3. Format date and time

The strftime() function can format a datetime object into a string in a specified format. The sample code is as follows:

from datetime import datetime


now = datetime.now()
formatted_datetime = now.strftime("%Y-%m-%d %H:%M:%S")
print("格式化日期和时间:", formatted_datetime)

4. Use timedelta to add and subtract time

The timedelta class represents a time interval or time difference, and can perform time addition and subtraction operations. The sample code is as follows:

from datetime import datetime, timedelta


now = datetime.now()
one_day = timedelta(days=1)
one_week_ago = now - one_day * 7
print("一周前的日期和时间:", one_week_ago)

3. calendar module

The calendar module is a module in the Python standard library for working with calendars. It provides calendar-related functions and classes that can be used to generate calendars, determine leap years, get the day of the week, and other operations.

1. Generate a calendar for the specified year

The calendar.calendar() function can generate a calendar string for a specified year. The sample code is as follows:

import calendar


cal = calendar.calendar(2023)
print("2023年的日历:", cal)

2. Generate a calendar for the specified year and month

The calendar.month() function can generate a calendar string for the specified year and month. The sample code is as follows:

import calendar


cal_month = calendar.month(2023, 9)
print("2023年9月的日历:", cal_month)

3. Determine whether the specified year is a leap year

The calendar.isleap() function can determine whether the specified year is a leap year. The sample code is as follows:

import calendar


is_leap = calendar.isleap(2023)
print("2023年是否是闰年:", is_leap)

4. Get the day of the week for a specified date

The calendar.weekday() function can return the day of the week for a specified date (0 means Monday, 6 means Sunday). The sample code is as follows:

import calendar


weekday = calendar.weekday(2023, 9, 12)
print("2023年9月12日是星期几:", weekday)

Through the above detailed explanation of the time, datetime and calendar modules, we understand their basic usage and common functions, and can easily process and operate dates and times. In actual development, we can select appropriate modules and functions according to specific needs to implement various date and time processing operations.

write at the end

If you encounter any problems while learning Python and would like to contact me directly to discuss Python-related issues, I am very willing to communicate with you. You can add my WeChat account by scanning the QR code below, and explain your learning needs and questions when adding. I will try my best to help you solve your problem and provide support.

Finally: The complete software testing video tutorial below has been compiled and uploaded. Friends who need it can get it by themselves [guaranteed 100% free]

Software Testing Interview Document

We must study to find a high-paying job. The following interview questions are from the latest interview materials from first-tier Internet companies such as Alibaba, Tencent, Byte, etc., and some Byte bosses have given authoritative answers. After finishing this set I believe everyone can find a satisfactory job based on the interview information.

Guess you like

Origin blog.csdn.net/wx17343624830/article/details/132838490