Home Backend Development Python Tutorial How to use the datetime module for date and time processing in Python 3.x

How to use the datetime module for date and time processing in Python 3.x

Jul 29, 2023 pm 09:53 PM
time processing Date processing datetime module

How to use the datetime module for date and time processing in Python 3.x

In Python programming, it is often necessary to process dates and times. Python's datetime module provides some powerful functionality for working with date and time objects. This article will introduce how to use the datetime module for date and time processing, and give some practical code examples.

  1. Import datetime module

To use the datetime module, you first need to import it:

import datetime
Copy after login
  1. Get the current date and time

Use the datetime.datetime.now() method to get the current date and time. The following code example demonstrates how to get the current date and time and print the output:

import datetime

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

Run the above code, the output is as follows:

当前日期和时间: 2022-01-01 12:34:56.789012
Copy after login
  1. Create an object with the specified date and time

You can use the datetime.datetime(year, month, day, hour, minute, second, microsecond) method to create a datetime object specifying the date and time. The following code example creates a datetime object and prints the output:

import datetime

dt = datetime.datetime(2021, 12, 31, 23, 59, 59, 999999)
print("指定的日期和时间:", dt)
Copy after login

Run the above code, the output is as follows:

指定的日期和时间: 2021-12-31 23:59:59.999999
Copy after login
  1. Get the various parts of the date and time

The datetime object has many properties and methods that can be used to obtain various parts of the date and time. The following code example demonstrates how to get the year, month, day, hour, minutes, seconds, and microseconds:

import datetime

now = datetime.datetime.now()

year = now.year
month = now.month
day = now.day
hour = now.hour
minute = now.minute
second = now.second
microsecond = now.microsecond

print("当前日期和时间:", now)
print("年:", year)
print("月:", month)
print("日:", day)
print("小时:", hour)
print("分钟:", minute)
print("秒:", second)
print("微秒:", microsecond)
Copy after login

Running the above code, the output is as follows:

当前日期和时间: 2022-01-01 12:34:56.789012
年: 2022
月: 1
日: 1
小时: 12
分钟: 34
秒: 56
微秒: 789012
Copy after login
  1. Date and time Addition and subtraction operations

The datetime object supports addition and subtraction operations for dates and times. You can use the timedelta object to specify the time intervals to be added or subtracted. The following code example demonstrates how to add and subtract dates and times:

import datetime

now = datetime.datetime.now()

one_day = datetime.timedelta(days=1)
yesterday = now - one_day
tomorrow = now + one_day

print("昨天:", yesterday)
print("明天:", tomorrow)

one_hour = datetime.timedelta(hours=1)
one_hour_later = now + one_hour
one_hour_ago = now - one_hour

print("一个小时前:", one_hour_ago)
print("一个小时后:", one_hour_later)
Copy after login

Run the above code and the output will be as follows:

昨天: 2021-12-31 12:34:56.789012
明天: 2022-01-02 12:34:56.789012
一个小时前: 2022-01-01 11:34:56.789012
一个小时后: 2022-01-01 13:34:56.789012
Copy after login
  1. Format dates and times

You can use the strftime() method to format a datetime object into a string. The following code example demonstrates how to format dates and times into different string representations:

import datetime

now = datetime.datetime.now()

# 输出日期部分
print("当前年月日:", now.strftime("%Y-%m-%d"))
print("当前月日年:", now.strftime("%m/%d/%Y"))

# 输出时间部分
print("当前时分秒:", now.strftime("%H:%M:%S"))
print("当前时分秒(12小时制):", now.strftime("%I:%M:%S %p"))
print("当前时分秒微秒:", now.strftime("%H:%M:%S.%f"))

# 输出星期几
print("当前星期几:", now.strftime("%A"))
Copy after login

Run the above code, the output is as follows:

当前年月日: 2022-01-01
当前月日年: 01/01/2022
当前时分秒: 12:34:56
当前时分秒(12小时制): 12:34:56 PM
当前时分秒微秒: 12:34:56.789012
当前星期几: Saturday
Copy after login

This article describes how to format dates and times in Python 3.x Use the datetime module for basic operations on date and time processing. Once you master these basics, you can more easily handle date and time data and develop time-related applications more efficiently. Hope this article is helpful to you!

The above is the detailed content of How to use the datetime module for date and time processing in Python 3.x. 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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 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)

Learn time processing in Go Learn time processing in Go Jul 21, 2023 am 10:38 AM

In programming, we often encounter the eight-hour time difference problem. This is caused by time zone differences, and in order to better resolve them, we need to understand several time definition standards. GMT Greenwich Mean Time. GMT calculates time based on the rotation and revolution of the Earth

What are the methods of time processing in Go language? What are the methods of time processing in Go language? Jun 10, 2023 pm 09:42 PM

As a modern programming language, Go language plays an important role in development. The Go language provides some built-in time functions and structures to make time processing more convenient. In this article, we will introduce some commonly used time processing methods in the Go language. time.Now() We can use the time.Now() function to get the current time: now:=time.Now()fmt.Println(now) output: 2019-06-131

How to deal with date and time issues in Python How to deal with date and time issues in Python Oct 09, 2023 am 09:29 AM

How to deal with date and time issues in Python requires specific code examples. Dealing with dates and times is a common task during development. Whether it is calculating the difference between two dates, formatting date strings, or performing time addition and subtraction operations, these are all requirements that are often encountered in development. Python provides a wealth of date and time processing libraries. This article will introduce how to use these libraries for date and time processing, and provide specific code examples. Python’s date and time processing libraries mainly include datetim

Date and time processing techniques in PHP Date and time processing techniques in PHP May 11, 2023 pm 12:22 PM

With the popularity of the Internet, the development of Web applications has attracted more and more attention. In these applications, date and time processing technology is a very important part. In PHP development, date and time processing involves many aspects, such as date formatting, time zone conversion, timestamp processing, etc. This article will introduce date and time processing technology in PHP in detail. 1. Basic concepts of date and time In PHP, date and time processing is achieved through built-in date and time functions. Before using these functions, we

Time and timestamp handling in PHP backend API development Time and timestamp handling in PHP backend API development Jun 17, 2023 pm 12:06 PM

With the development of Internet applications, more and more systems need to process time-related data, such as log records, scheduled tasks, etc. In PHP back-end API development, the processing of time and timestamps is a very important part. This article will introduce the basic concepts of time and timestamps in PHP, how to use them, and solutions to some common problems. 1. Basic concepts of time and timestamps Time refers to a specific moment or period, usually expressed in the form of year, month, day, hour, minute, second, etc. Timestamp refers to the time from a fixed point in time (such as

How to use the datetime module for date and time processing in Python 3.x How to use the datetime module for date and time processing in Python 3.x Jul 29, 2023 pm 09:53 PM

How to use the datetime module for date and time processing in Python3.x In Python programming, it is often necessary to process dates and times. Python's datetime module provides some powerful functions for working with date and time objects. This article will introduce how to use the datetime module for date and time processing, and give some practical code examples. To import the datetime module, use the datetime module

PHP and Vue.js development tips: How to handle statistical charts of date and time data PHP and Vue.js development tips: How to handle statistical charts of date and time data Aug 19, 2023 am 08:10 AM

PHP and Vue.js development tips: How to process statistical charts of date and time data Introduction: In the process of web development, processing statistical charts of date and time data is a very common requirement. The combination of PHP and Vue.js is a powerful tool that can easily handle and display charts of date and time data. This article will introduce some useful tips and sample code to help readers better handle date and time data during development. 1. Date and time processing functions in PHP: In PHP, there are some built-in

How to find files in Linux How to find files in Linux Jul 31, 2023 pm 01:19 PM

How to find files in Linux: 1. Use the find command; 2. Use the locate command; 3. Use the grep command; use the whereis command.

See all articles