search
HomeBackend DevelopmentPython TutorialHow 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.

Since the

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

2. Extension: January 1, 1970 Day

Contemporary computer systems have a timekeeping function capable of outputting the day## from Greenwich Mean Time

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

64

bits. 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

datetime

class (

datetime.datetime

class, 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()

Function: Return a

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. Use
datetime utcnow()

Obtain the

UTC
(Universal Standard Time) time object corresponding to the current date and time. The usage method is as follows:

datetime.utcnow ()
Function: Return a datetime type, representing The UTC

representation of 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.utcnow()
print(today)
2022-05-01 12:35:40.849860

3.
datetime.now()

and

datetime utcnow()
both return an object of type

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)
Function: Returns a datetime type, representing the specified date and time, which can be accurate to microseconds.

The parameters are as follows:

year

: the specified year,

MINYEAR

year MAXYEARmonth: The specified month, 1 month 12day: The specified date, 1 day hour: The specified hour, 0 hour 24minute :The specified number of minutes, 0 minute 60

second:指定的秒数,0 second

60

microsecond:指定的微秒数,0 microsecond

1000000

其中,hourminutesecondmicrosecond 参数可以全部或部分省略。

调用 datetime() 函数直接创建一个 datetime 对象,表示 20225120:33327 微妙,执行结果如下:

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!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Python's Execution Model: Compiled, Interpreted, or Both?Python's Execution Model: Compiled, Interpreted, or Both?May 10, 2025 am 12:04 AM

Pythonisbothcompiledandinterpreted.WhenyourunaPythonscript,itisfirstcompiledintobytecode,whichisthenexecutedbythePythonVirtualMachine(PVM).Thishybridapproachallowsforplatform-independentcodebutcanbeslowerthannativemachinecodeexecution.

Is Python executed line by line?Is Python executed line by line?May 10, 2025 am 12:03 AM

Python is not strictly line-by-line execution, but is optimized and conditional execution based on the interpreter mechanism. The interpreter converts the code to bytecode, executed by the PVM, and may precompile constant expressions or optimize loops. Understanding these mechanisms helps optimize code and improve efficiency.

What are the alternatives to concatenate two lists in Python?What are the alternatives to concatenate two lists in Python?May 09, 2025 am 12:16 AM

There are many methods to connect two lists in Python: 1. Use operators, which are simple but inefficient in large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use the = operator, which is both efficient and readable; 4. Use itertools.chain function, which is memory efficient but requires additional import; 5. Use list parsing, which is elegant but may be too complex. The selection method should be based on the code context and requirements.

Python: Efficient Ways to Merge Two ListsPython: Efficient Ways to Merge Two ListsMay 09, 2025 am 12:15 AM

There are many ways to merge Python lists: 1. Use operators, which are simple but not memory efficient for large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use itertools.chain, which is suitable for large data sets; 4. Use * operator, merge small to medium-sized lists in one line of code; 5. Use numpy.concatenate, which is suitable for large data sets and scenarios with high performance requirements; 6. Use append method, which is suitable for small lists but is inefficient. When selecting a method, you need to consider the list size and application scenarios.

Compiled vs Interpreted Languages: pros and consCompiled vs Interpreted Languages: pros and consMay 09, 2025 am 12:06 AM

Compiledlanguagesofferspeedandsecurity,whileinterpretedlanguagesprovideeaseofuseandportability.1)CompiledlanguageslikeC arefasterandsecurebuthavelongerdevelopmentcyclesandplatformdependency.2)InterpretedlanguageslikePythonareeasiertouseandmoreportab

Python: For and While Loops, the most complete guidePython: For and While Loops, the most complete guideMay 09, 2025 am 12:05 AM

In Python, a for loop is used to traverse iterable objects, and a while loop is used to perform operations repeatedly when the condition is satisfied. 1) For loop example: traverse the list and print the elements. 2) While loop example: guess the number game until you guess it right. Mastering cycle principles and optimization techniques can improve code efficiency and reliability.

Python concatenate lists into a stringPython concatenate lists into a stringMay 09, 2025 am 12:02 AM

To concatenate a list into a string, using the join() method in Python is the best choice. 1) Use the join() method to concatenate the list elements into a string, such as ''.join(my_list). 2) For a list containing numbers, convert map(str, numbers) into a string before concatenating. 3) You can use generator expressions for complex formatting, such as ','.join(f'({fruit})'forfruitinfruits). 4) When processing mixed data types, use map(str, mixed_list) to ensure that all elements can be converted into strings. 5) For large lists, use ''.join(large_li

Python's Hybrid Approach: Compilation and Interpretation CombinedPython's Hybrid Approach: Compilation and Interpretation CombinedMay 08, 2025 am 12:16 AM

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

See all articles

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

Video Face Swap

Video Face Swap

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

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software