Home  >  Article  >  Backend Development  >  How to use the Python datetime library

How to use the Python datetime library

WBOY
WBOYforward
2023-05-27 12:11:161677browse

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 <=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

其中,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:yisu.com. If there is any infringement, please contact admin@php.cn delete