How to use the Python datetime library
1. Datetime library overview
Displaying dates and times in different formats is the most commonly used function in programs. Python provides a standard function library for time processing datetime, which provides a series of time processing methods from simple to complex.
datetime The library can obtain the time from the system and output it in a user-selected format.
datetime The library is based on Greenwich Mean Time, with each day accurately defined by 3600X24 seconds. The library includes two constants: datetime.MINYEAR and datetime.MAXYEAR, which respectively represent the minimum and maximum year that datetime can represent, and their values are ## respectively. #1 and 9999.
datetime The library provides a variety of date and time expressions in the form of classes.
(1) datetime.date: Date representation class, which can represent year, month, day, etc.(2) datetime.time: Time representation class, which can represent hours, minutes, seconds, milliseconds, etc.
(3) datetime.dateime: A class representing date and time, with functions covering date and time classes.
(4) datetime.timedelta: Classes related to time intervals.
(5) datetime.tzinfo: Information representation class related to time zone.
datetime.daetime class has the most abundant expression forms, here we mainly introduce the use of this class. To use the datetime class, you need to use the import reserved word. The way to reference the datetime class is as follows:
from datetime import datetime
1970year1month1 #00:00:00 Counting the time from the beginning to the present, accurate to seconds, is an early design habit of the UNIX operating system, and is later used in all computer systems. Today's computer hardware and systems are all
64bits. If 64 bits are used to store this time count, the maximum distance can be represented by 1970 years. 1 The 264 seconds starting from the 1 day, the total number of seconds in the 1 year 365 day is approximately 1.9x224, therefore, 64 computer systems can represent time to approximately 239 AD, I believe our N generations of descendants, even if There is no need to worry about inaccurate time until the day the earth is destroyed. ——Why choose to start from
1970, month 1? ——No matter which day you choose to start from, They all have the same problem, right?3. The datetime library parses the
datetimeclass (
datetime.datetimeclass, hereafter referred to as # The way to use the ##datetime class) is to first create a datetime object, and then display the time through the object's methods and properties. There are three methods for creating datetime objects: datetime.now(), datetime.utcnow() and datetime.datetime(). 1. Use datetime.now() to obtain the current date and time object. The usage method is as follows:
datetime.now()
datetime type , represents the current date and time, accurate to microseconds. Parameters: None Call this function, the execution result is as follows:
from datetime import datetime today = datetime.now() print(today)
2022-05-01 20:32:41.772021
2. Usedatetime utcnow()(Universal Standard Time) time object corresponding to the current date and time. The usage method is as follows:Obtain the
UTC
datetime.utcnow ()
from datetime import datetime today = datetime.utcnow() print(today)
datetime.now()both return an object of typeand
datetime utcnow()
datetime, you can also directly use datetime() to construct a date and time object, using the method As follows:
datetime (year, month, day, hour=0, minute=0,second=0, microsecond=0)
year
: the specified year,MINYEAR
<=year <= MAXYEARmonth: The specified month, 1
<=month <= 12day: The specified date, 1
<=day <=The upper limit of the date corresponding to the monthhour: The specified hour, 0
<=hour < 24minute :The specified number of minutes, 0
<=minute < 60
second:指定的秒数,0 <= second < 60
microsecond:指定的微秒数,0 <= microsecond < 1000000
其中,hour、minute、second、microsecond 参数可以全部或部分省略。
调用 datetime() 函数直接创建一个 datetime 对象,表示 2022 年 5 日 1 日 20:33,32 秒 7 微妙,执行结果如下:
from datetime import datetime someday = datetime(2022, 5, 1, 20, 43, 32, 7) print(someday)
2022-05-01 20:43:32.000007
到此,程序已经有了一个 datetime 对象,进一步可以利用这个对象的属性显示时间,为了区别 datetime 库名,采用上例中的 someday 代替生成的 datetime 对象,常用属性如下表所示。
属性 | 描述 |
someday.min | 固定返回 datetime 的最小时间对象,datetime(1,1,1,0,0) |
someday.max | 固定返回 datetime 的最大时间对象,datetime(9999,12,31,23,59,59,59,999999) |
someday.year | 返回 someday 包含的年份 |
someday.month | 返回 someday 包含的月份 |
someday.day | 返回 someday 包含的日期 |
someday.hour | 返回 someday 包含的小时 |
someday.minute | 返回 someday 包含的分钟 |
someday.second | 返回 someday 包含的秒钟 |
someday.microsecond | 返回 someday 包含的微妙值 |
datetime 对象有 3 个常用的时间格式化方法,如下表所示
属性 | 描述 |
someday.isoformat() | 采用 ISO 8601 标准显示时间 |
someday.isoweekday() | 根据日期计算星期后返回 1~7,对应星期一到星期日 |
someday.strftime(format) | 根据格式化字符串 format 进行格式显示的方法 |
isoformat() 和 isoweekday() 方法的使用如下:
from datetime import datetime today = datetime.now() print(today.isoformat()) print(today.isoweekday())
程序执行结果如下:
2022-05-01T21:00:28.392304
7
strftime() 方法是时间格式化最有效的方法,几乎可以以任何通用格式输出时间。例如下面的例子,用该方法输出特定格式时间。
from datetime import datetime today = datetime.now() print(today.strftime("%Y-%m-%d %H : %M : %S"))
程序执行结果如下:
2022-05-01 21 : 04 : 23
下表是 strftime() 方法的格式化控制符。
格式化字符串 | 日期/时间 | 值范围和实例 |
%Y | 年份 | 0001~9999 |
%m | 月份 | 01~12 |
%B | 月名 | January~December |
%b | 月名缩写 | Jan~Dec |
%d | 日期 | 01~31 |
%A | 星期 | Monday~Sunday |
%a | 星期缩写 | Mon~Sun |
%H | 小时(24 h 制) | 00~23 |
%M | 分钟 | 00~59 |
%S | 秒 | 00~59 |
%x | 日期 | 月/日/年,例如,01/01/2022 |
%X | 时间 | 时 :分:秒,例如,19 : 09 : 31 |
strftime() 格式化字符串的数字左侧会自动补零,上述格式也可以与 print() 的格式化函数起使用,例如:
from datetime import datetime now = datetime.now() print(now.strftime("%Y- %m- %d")) print(now.strftime("%A,%d. %B %Y %H: %M%p")) print("今天是 {0:%Y} 年 {0:%m} 月 {0:%d} 日".format(now))
程序执行结果如下:
2022- 05- 01
Sunday,01. May 2022 21: 21PM
今天是 2022 年 05 月 01 日
datetime 库主要用于对时间的表示,从格式化角度掌握 strftime() 函数已经能够处理很多情况了。建议读者在遇到需要处理时间的问题时采用 datetime 库,简化格式输出和时间的维护。
The above is the detailed content of How to use the Python datetime library. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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.

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.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

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.

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.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
