首頁  >  文章  >  後端開發  >  Python 日期和時間用法超強總結

Python 日期和時間用法超強總結

WBOY
WBOY轉載
2023-04-13 10:58:081337瀏覽

時間無疑是生活各個方面中最關鍵的因素之一,因此,記錄和追蹤時間變得非常重要。在 Python 中,可以透過其內建程式庫追蹤日期和時間。今天我們來介紹關於 Python 中的日期和時間,一起來了解如何使用time和datetime模組來尋找和修改日期和時間。

Python 中處理日期和時間的模組

Python 提供了time和datetime模組,可以幫助我們輕鬆取得和修改日期和時間,讓我們逐一了解以下。

time 模組

該模組包括使用時間執行各種操作所需的所有與時間相關的功能,它還允許我們存取多種用途所需的時鐘類型。

內建函數:

請看下表,它描述了時間模組的一些重要內建功能。

程式碼格式化:

在用範例解釋每個函數之前,先看一下所有合法的格式化程式碼的方式:

function

Description

time()

傳回自epoch以來經過的秒數

ctime()

以經過的秒數為參數,傳回目前日期和時間

sleep ()

在給定的持續時間內停止執行緒的執行

time.struct_time Class

函數要么將此類作為參數,要么將其作為輸出返回

localtime()

以自epoch以來經過的秒數作為參數,並以時間形式傳回日期和時間。 struct_time格式

gmtime()

與localtime()類似,回傳時間。 UTC格式的struct_time

mktime()

ocaltime()的倒數。取得包含9個參數的元組,並傳回自epoch pas輸出以來經過的秒數

asctime()

##取得包含9個參數的元組,並傳回表示相同參數的字串

#strftime()

取得包含9個參數的元組,並根據使用的格式代碼傳回表示相同參數的字串

#strptime()

分析字串並及時返回。 struct_time格式

##Example %a#Weekday (short version)MonMondayAugAugust#描繪該月的某一天(01-31)07微秒#000000-999999小時(00-23)15#小時(00-11)#323#一年中從星期日開始的週數(00-53)12##一週中的星期幾##22%Y年(完整版)2022%zUTC 偏移量 0100%Z時區##

struct_time 類別具有下列屬性:

##Code

#Description

##Weekday (short version)

%A

#Weekday (full version)

%b

Month (short version)

#%B

Month (full version)

%c

######Local date and time version###

2019 年8 月23 日星期二1:31:40

##%d

#%f

.%H

%I

#########% j########## ###一年中的第幾天############235################# #%m########## ##月份號碼(01-12)###

07

%M

分鐘 (00-59)

44

%p

早上/下午

AM

%S

%S

%U

%w

星期一(1)

######%W######## # ###一年中的週數,從星期一開始(00-53)###

34

%x

本機日期

##06/07/22

%X

當地時間

12:30:45

%y

年(短版)

CST

%%

% 字元

%

#

現在讓我們來看幾個 time 模組的例子。

使用time模組尋找日期和時間

使用上表中所述的內建函數和格式化程式碼,可以在 Python 中輕鬆取得日期和時間。

import time
#time
a=time.time() #total seconds since epoch
print("Seconds since epoch :",a,end='n----------n')
#ctime
print("Current date and time:")
print(time.ctime(a),end='n----------n') 
#sleep
time.sleep(1) #execution will be delayed by one second
#localtime
print("Local time :")
print(time.localtime(a),end='n----------n')
#gmtime
print("Local time in UTC format :")
print(time.gmtime(a),end='n-----------n')
#mktime
b=(2019,8,6,10,40,34,1,218,0)
print("Current Time in seconds :")
print( time.mktime(b),end='n----------n')
#asctime
print("Current Time in local format :")
print( time.asctime(b),end='n----------n')
#strftime
c = time.localtime() # get struct_time
d = time.strftime("%m/%d/%Y, %H:%M:%S", c)
print("String representing date and time:")
print(d,end='n----------n')
#strptime
print("time.strptime parses string and returns it in struct_time format :n")
e = "06 AUGUST, 2019"
f = time.strptime(e, "%d %B, %Y")
print(f)

Output:

Seconds since epoch : 1565070251.7134922
———-
Current date and time:
Tue Aug 6 11:14:11 2019
———-
Local time :
time.struct_time(tm_year=2019, tm_mon=8, tm_mday=6, tm_hour=11, tm_min=14, tm_sec=11, tm_wday=1, tm_yday=218, tm_isdst=0)
———-
Local time in UTC format :
time.struct_time(tm_year=2019, tm_mon=8, tm_mday=6, tm_hour=5, tm_min=44, tm_sec=11, tm_wday=1, tm_yday=218, tm_isdst=0)
———–
Current Time in seconds :
1565068234.0
———-
Current Time in local format :
Tue Aug 6 10:40:34 2019
———-
String representing date and time:
08/06/2019, 11:14:12
———-
time.strptime parses string and returns it in struct_time format :

time.struct_time(tm_year=2019, tm_mon=8, tm_mday=6, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=218, tm_isdst=-1)

datetime 模組

#與time模組類似,datetime模組包含處理日期和時間所必需的所有方法。

內建功能:

下表介紹了本模組中的一些重要功能:

#Attribute

Value

tm_year

#0000, .., 2019, …, 9999

tm_mon

1-12

tm_mday

1-31

#tm_hour

#########0-23#### ##############tm_min############0-59##################tm_sec# ###########0-61###################tm_wday############0-6  (Monday is 0)##################tm_yday###
##1-366

#tm_isdst

0, 1, -1    (夏令時,未知時為-1)

function

Description

#datetime()

datetime 的建構子

datetime.today()

傳回目前本機日期和時間

datetime.now()

#傳回目前本機日期和時間

date()

以年、月、日為參數,建立對應的日期

time()

以小時、分鐘、秒、微秒和tzinfo作為參數,並建立對應的日期

##date.fromtimestamp()

轉換秒數以傳回對應的日期和時間

timedelta()

它是不同日期或时间之间的差异(持续时间)

使用 datetime 查找日期和时间

现在,让我们尝试实现这些函数,以使用datetime模块在 Python 中查找日期和时间。

import datetime
#datetime constructor
print("Datetime constructor:n")
print(datetime.datetime(2019,5,3,8,45,30,234),end='n----------n')
 
#today
print("The current date and time using today :n")
print(datetime.datetime.today(),end='n----------n')
 
#now
print("The current date and time using today :n")
print(datetime.datetime.now(),end='n----------n')
 
#date
print("Setting date :n")
print(datetime.date(2019,11,7),end='n----------n')

#time
print("Setting time :n")
print(datetime.time(6,30,23),end='n----------n')
 
#date.fromtimestamp
print("Converting seconds to date and time:n")
print(datetime.date.fromtimestamp(23456789),end='n----------n')
 
#timedelta
b1=datetime.timedelta(days=30, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=4, weeks=8)
b2=datetime.timedelta(days=3, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=4, weeks=8)
b3=b2-b1
print(type(b3))
print("The resultant duration = ",b3,end='n----------n')
 
#attributes
a=datetime.datetime.now() #1
print(a)
print("The year is :",a.year)
 
print("Hours :",a.hour)

Output:

Datetime constructor:

2019-05-03 08:45:30.000234
———-
The current date and time using today :

2019-08-06 13:09:56.651691
———-
The current date and time using today :

2019-08-06 13:09:56.651691
———-
Setting date :

2019-11-07
———-
Setting time :

06:30:23
———-
Converting seconds to date and time:
1970-09-29
———-
<class ‘datetime.timedelta’>
The resultant duration = -27 days, 0:00:00
———-
2019-08-06 13:09:56.653694
The year is : 2019
Hours : 13

以上是Python 日期和時間用法超強總結的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:51cto.com。如有侵權,請聯絡admin@php.cn刪除