ホームページ  >  記事  >  バックエンド開発  >  Pythonの日付と時刻の使い方の超まとめ

Pythonの日付と時刻の使い方の超まとめ

WBOY
WBOY転載
2023-04-13 10:58:081337ブラウズ

時間は人生のあらゆる側面において間違いなく最も重要な要素の 1 つであるため、時間を記録し追跡することが非常に重要になります。 Python では、組み込みライブラリを通じて日付と時刻を追跡できます。今日は、Python の日付と時刻について紹介し、time モジュールと datetime モジュールを使用して日付と時刻を検索および変更する方法を学びます。

Python で日付と時刻を処理するモジュール

Python には、日付と時刻を簡単に取得および変更できる time モジュールと datetime モジュールが用意されています。

time モジュール

このモジュールには、時間を使用してさまざまな操作を実行するために必要な時間関連の関数がすべて含まれています。また、複数の目的に必要なクロック タイプにアクセスすることもできます。

組み込み関数:

time モジュールのいくつかの重要な組み込み関数について説明した次の表をご覧ください。

##time.struct_time Class関数は、このクラスをパラメータとして受け取るか、出力として返します。localtime()エポックからの経過秒数をパラメータとして受け取り、日付と時刻を時間の形式で返します。 struct_time 形式##gmtime()

コードの書式設定:

各関数を例を挙げて説明する前に、コードを書式設定するためのすべての合法的な方法を見てみましょう:

関数

説明

time()

エポックから経過した秒数を返します

ctime()

は経過秒数をパラメータとして受け取り、現在の日付と時刻を返します

sleep ()

指定された期間、スレッドの実行を停止します

localtime() と同様に、時間を返します。 UTC 形式の struct_time

mktime()

ocaltime() の逆数。 9 個のパラメータを含むタプルを取得し、エポックパス出力からの経過秒数を返します。

#asctime()

9 個のパラメータを含むタプルを取得し、同じパラメータを表す文字列を返します

strftime()

タプルを取得します9 つのパラメータを含み、使用される形式コードに従って同じパラメータを表す文字列を返します。

#strptime()

文字列を分析し、時間内に返します。 struct_time 形式

##平日 (短縮版)#%A##月 (短縮版)月 (フルバージョン)#AM%S秒 (00-59)23%U日曜日から始まる年の週番号(00-53)12%w週の曜日番号月曜日 (1)%W月曜日から始まる年の週番号 (00-53)##12:30:45%y年 (短縮版)22%Y年 (完全版)2022%zUTC オフセット 0100%Zタイムゾーン

struct_time クラスには次の属性があります:

コード

説明

#%a

##月

平日 (フルバージョン)

月曜日

#%b

##8 月

%B

8 月

##%c

ローカルの日付と時刻のバージョン

火曜日 8 月 23 日 1:31:40 2019

%d

描写月の日 (01-31)

07

%f

マイクロ秒

000000-999999

%H

##時間 (00-23)

15

%I

時間 (00-11)

3

%j

今年の日

235

%m

月番号 (01-12)

#07

%MM

分 (00-59)

44

%p

午前 / 午後

#34

%x

現地の日付

06/07/22

%X

現地時間

#CST

%%

% 文字

#%

##0000, .., 2019, …, 9999tm_mon1-12tm_mdaytm_hour#tm_min0-610-6 (月曜日は0)#

次に、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)

出力:

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 module

time モジュールと同様に、datetime モジュールには日付と時刻を処理するために必要なすべてのメソッドが含まれています。

組み込み関数:

次の表では、このモジュールの重要な関数をいくつか紹介します:

##Attribute

Value

tm_year

#1-31

0-23

#0-59

##tm_sec

tm_wday

#tm_yday

1-366

tm_isdst

0、1、-1 (夏時間、不明の場合は -1)

##datetime.today()現在のローカル日付と時刻を返しますdatetime.now()現在のローカル日付と時刻を返しますdate() 年、月、日をパラメータとして取得し、対応する日付を作成しますtime()時間、分、秒、マイクロ秒、tzinfo をパラメータとして受け取り、対応する日付を作成しますdate.fromtimestamp()

function

説明

##datetime()

datetime のコンストラクター

秒を変換して対応する日付と時刻を返します

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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事は51cto.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。